我有一个像下面这样的JSON对象,我想获得每个属性的唯一名称列表 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
}
我的JSON路径查询应该返回
"store","book","category","author","title","price","isbn","bicycle","color","expensive"
如何表达JSON Path查询以获取属性列表?
答案 0 :(得分: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示例。