JSON.stringify替换器-如何获取完整路径 [英] JSON.stringify replacer - how to get full path

查看:48
本文介绍了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为此

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: https://stackoverflow.com/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替换器-如何获取完整路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆