kellyfj
kellyfj

Reputation: 6943

In a JSON object how do I get a list of all unique attribute names via JSON path

I have a JSON object like the following and I want to get a list of the unique names of each of the attributes e.g.

    {
    "store": {
        "book": [
            {
                "category": "reference",
                "author": "Nigel Rees",
                "title": "Sayings of the Century",
                "price": 8.95
            },
            {
                "category": "fiction",
                "author": "J. R. R. Tolkien",
                "title": "The Lord of the Rings",
                "isbn": "0-395-19395-8",
                "price": 22.99
            }
        ],
        "bicycle": {
            "color": "red",
            "price": 19.95
        }
    },
    "expensive": 10
}

My JSON path query should return

"store","book","category","author","title","price","isbn","bicycle","color","expensive"

How would I express a JSON Path query to get that list of attributes?

Upvotes: 3

Views: 1726

Answers (1)

atrifan
atrifan

Reputation: 172

var keys = [];
function recursiveParser(obj) {
     if(!obj) {
       return;
     }
     if(obj.constructor == Array) { //if it's an array than parse every element of it
       for(var i = 0; i < obj.length; i++) {
         recursiveParser(obj[i]); 
       }
     } else if(obj.constructor == Object) { //if it's json
       for(var key in obj) { //for each key
         if(keys.indexOf(key) === -1) { // if you don't have it
             keys.push(key); //store it
             recursiveParser(obj[key]); //give the value of the key to the parser
         } else {
             recursiveParser(obj[key]); //if you do have it pass the value of the key anyway to the parser
         }
       }
     }
}
console.log(keys); //show results

This would be my solution. I will come back with a jsfiddle example of the code.

Example of working code: http://jsfiddle.net/atrifan/0d99u7hj/2

Upvotes: 1

Related Questions