在一个JSON对象中,如何通过JSON路径获取所有唯一属性名称的列表?

3

我有一个类似以下的JSON对象,我想获得每个属性唯一名称的列表,例如:

    {
    "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
}

我的JSON路径查询应该返回

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

我该如何表达一个JSON Path查询,以获取那个属性列表?
1个回答

1
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

这是我的解决方案。我将回来提供一个jsfiddle代码示例。
工作代码示例:http://jsfiddle.net/atrifan/0d99u7hj/2

3
谢谢 - 是的,我想我总能做类似的事情,但我特别在寻找一种JSON路径解决方案。 - kellyfj

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接