Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To print all the paths in a json object

What is the easy way to get all paths in the Given Json Object; For Example:

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

I should able to produce 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 is there any built in function from json which does this.

like image 250
Ysak Avatar asked Dec 02 '15 06:12

Ysak


People also ask

How do I print the value of a JSON object?

Printing a JSON value to the pagePrinting the value involves a little bit of JavaScript (or jQuery to make it easier). (In the above code, replace APIKEY with your actual API key.) (In the above code, replace APIKEY with your actual API key.) Refresh the page and you will see the wind speed printed to the page.

What is JSON () in JavaScript?

JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page, or vice versa).

Can you use wildcards in JSON?

JSON Path wildcard syntax IMPORTANT Assertible's JSON Path syntax supports wildcards in the path. Only single node selections are valid using pure json path. If you need more advanced scripting capabilities, use the . jq() function.


1 Answers

You can implement your custom converter by iterating through objects recursively.

Something like this:

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');

That's not a best converter implementation, just a fast-written example, but it should help you to understand the main principle.

Here is the working JSFiddle demo.

like image 190
Yeldar Kurmangaliyev Avatar answered Oct 02 '22 21:10

Yeldar Kurmangaliyev