JSON.stringify替换器

编程入门 行业动态 更新时间:2024-10-24 14:23:47
本文介绍了JSON.stringify替换器-如何获取完整路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

下面代码中的替换器在控制台上写入当前处理的字段名称

Replacer in below code write on console current processed field name

let a = { a1: 1, a2:1 } let b = { b1: 2, b2: [1,a] } let c = { c1: 3, c2: b } let s = JSON.stringify(c, function (field,value) { console.log(field); // full path... ??? return value; });

但是我想获得替换器函数中字段的完整路径"(不仅是其名称),就像这样

However I would like to get full "path" to field (not only its name) inside replacer function - something like this

c1 c2 c2.b1 c2.b2 c2.b2[0] c2.b2[1] c2.b2[1].a1 c2.b2[1].a2

该怎么做?

推荐答案

装饰器 代码段中的

replacerWithPath使用this确定路径(感谢@Andreas为此提示),field和value以及执行过程中存储的一些历史数据(此解决方案支持数组)

Decorator

replacerWithPath in snippet determine path using this (thanks @Andreas for this tip ), field and value and some historical data stored during execution (and this solution support arrays)

JSON.stringify(c, replacerWithPath(function(field,value,path) { console.log(path,'=',value); return value; }));

function replacerWithPath(replacer) { let m = new Map(); return function(field, value) { let path= m.get(this) + (Array.isArray(this) ? `[${field}]` : '.' + field); if (value===Object(value)) m.set(value, path); return replacer.call(this, field, value, path.replace(/undefined\.\.?/,'')) } } // Explanation fo replacerWithPath decorator: // > 'this' inside 'return function' point to field parent object // (JSON.stringify execute replacer like that) // > 'path' contains path to current field based on parent ('this') path // previously saved in Map // > during path generation we check is parent ('this') array or object // and chose: "[field]" or ".field" // > in Map we store current 'path' for given 'field' only if it // is obj or arr in this way path to each parent is stored in Map. // We don't need to store path to simple types (number, bool, str,...) // because they never will have children // > value===Object(value) -> is true if value is object or array // (more: stackoverflow/a/22482737/860099) // > path for main object parent is set as 'undefined.' so we cut out that // prefix at the end ad call replacer with that path // ---------------- // TEST // ---------------- let a = { a1: 1, a2: 1 }; let b = { b1: 2, b2: [1, a] }; let c = { c1: 3, c2: b }; let s = JSON.stringify(c, replacerWithPath(function(field, value, path) { // "this" has same value as in replacer without decoration console.log(path); return value; }));

奖金:我使用这种方法在此处

BONUS: I use this approach to stringify objects with circular references here

更多推荐

JSON.stringify替换器

本文发布于:2023-11-30 05:35:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648898.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:JSON   stringify

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!