我需要获取json的xpath(即,基本上),我需要获取json的密钥及其xpath。
var json='"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML",
"XML"]
},
"GlossSee": "markup"
}
}
}
}
Object.keys(json)
上面的代码返回父结构的键,如下所示。
[ 'glossary' ]
我需要所有键以及路径,我被困在这里,任何解决方案都将非常有帮助
最佳答案
也许这就是您想要的:
var json={"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML",
"XML"]
},
"GlossSee": "markup"
}
}
}
}};
function getKeys(keys, obj, path) {
for(key in obj) {
var currpath = path+'/'+key;
keys.push([key, currpath]);
if(typeof(obj[key]) == 'object' && !(obj[key] instanceof Array))
getKeys(keys, obj[key], currpath);
}
}
var keys = [];
getKeys(keys, json, '');
for(var i=0; i<keys.length; i++)
console.log(keys[i][0] + '=' + keys[i][1]);
结果是:
词汇表= /词汇表
标题= /词汇表/标题
GlossDiv = /词汇表/ GlossDiv
标题= /词汇表/ GlossDiv /标题
GlossList = /词汇表/ GlossDiv / GlossList
GlossEntry = /词汇表/ GlossDiv / GlossList / GlossEntry
ID = /词汇表/ GlossDiv / GlossList / GlossEntry / ID
SortAs = /词汇表/ GlossDiv / GlossList / GlossEntry / SortAs
...
关于javascript - 获取JSON对象的子项名称,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16834236/