To print all paths in json object

What is an easy way to get all the paths in a given Json object; For instance:

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

I could create the following object

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

I was able to achieve the same using a recursive function. I want to know if there is a built-in function from json that does this.

+5
source share
2 answers

You can implement your own converter by repeating objects recursively.

Something like that:

 var YsakON = { // YsakObjectNotation stringify: function(o, prefix) { prefix = prefix || ''; 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'; } } }; // Usage: YaskON.stringify(obj); 

This is not the best implementation of the converter, just a quick script, but it should help you understand the main principle.

Below is a working demo of JSFiddle .

+4
source

I think there is no built-in function that does this. This can be done with a simple loop, as shown below in my fiddle. But he does not care about recursion. Here are other posts I found regarding the same: Post1 and Post2 and 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

+1
source

Source: https://habr.com/ru/post/1237220/


All Articles