打印json对象中的所有路径

To print all the paths in a json object

本文关键字:路径 json 对象 打印      更新时间:2023-09-26

在Given Json对象中获取所有路径的简单方法是什么;例如:

{  
   app:{  
      profiles:'default'
   },
   application:{  
      name:'Master Service',
      id:'server-master'
   },
   server:{  
      protocol:'http',
      host:'localhost',
      port:8098,
      context:null
   }
}

我应该能够产生以下对象

app.profiles=default
application.name=Master Service
application.id=server-master

我能够使用递归函数实现同样的效果。我想知道json中是否有内置函数可以做到这一点。

您可以通过递归迭代对象来实现自定义转换器。

类似这样的东西:

var YsakON = { // YsakObjectNotation
  stringify: function(o, prefix) {          
    prefix = prefix || 'root';
    
    switch (typeof o)
    {
      case 'object':
        if (Array.isArray(o))
          return prefix + '=' + JSON.stringify(o) + ''n';
        
        var output = ""; 
        for (var k in o)
        {
          if (o.hasOwnProperty(k)) 
            output += this.stringify(o[k], prefix + '.' + k);
        }
        return output;
      case 'function':
        return "";
      default:
        return prefix + '=' + o + ''n';
    }   
  }
};
var o = {
	a: 1,
  b: true,
  c: {
    d: [1, 2, 3]
  },
  calc: 1+2+3,
  f: function(x) { // ignored
    
  }
};
document.body.innerText = YsakON.stringify(o, 'o');

这不是一个最好的转换器实现,只是一个快速编写的示例,但它应该有助于您理解主要原理。

这是正在运行的JSFiddle演示。

我认为没有内置函数可以做到这一点。这可以用一个简单的for循环来完成,如下所示。但它不考虑递归性。以下是我发现的关于相同的其他帖子:Post1和Post2以及Post3

var myjson = {  
   app:{  
      profiles:'default'
   },
   application:{  
      name:'Master Service',
      id:'server-master'
   },
   server:{  
      protocol:'http',
      host:'localhost',
      port:8098,
      context:null
   }
};
for(key in myjson) {  
  for(k in myjson[key]) {
    console.log(key + '.' + k + ' = '+ myjson[key][k]);
  }  
}

Fiddle

var obj1 = {
    "name" : "jane",
    "job" : {
        "first" : "nurse",
        "second" : "bartender",
        "last" : {
            "location" : "Paris",
            "work" : ["sleep", "eat", "fish", {"math" : "morning", "chem" : "late night"}],
            "read_books": {
                "duration" : 10,
                "books_read" : [{"title" : "Gone with the wind", "author": "I don't know"}, {"title": "Twologht", "author": "Some guy"}]
            }
        }
    },
    "pets": ["cow", "horse", "mr. peanutbutter"],
    "bf" : ["jake", "beatles", {"johnson": ["big johnson", "lil johnson"]}]    
}
var obj2 = ["jane", "jake", {"age" : 900, "location": "north pole", "name" : "Jim", "pets" : "..."}];
var allRoutes = [];
function findTree(o, parentKey = '', parentObject)
{
    if (typeof o !== 'object')
    {
        if (parentKey.substr(0,1) === '.')
            allRoutes.push(parentKey.substr(1));
        else
        allRoutes.push(parentKey);
        return;
    }
    let keys = Object.keys(o);
    for (let k in keys)
    {
        findTree(o[keys[k]], Array.isArray(o) ? parentKey + "[" +keys[k] + "]" :  parentKey + "." +keys[k], o);     
        //findTree(o[keys[k]], parentKey + "[" +keys[k] + "]");     
    }
}
findTree(obj1);

试试这个。