Reputation: 1981
I need to get the xpath of json (ie) basically i need to get the keys of the jsons along with its 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)
The above code returns the key of the parent structure as below.
[ 'glossary' ]
I need all the keys along with the path.
Upvotes: 0
Views: 11603
Reputation: 1
You can do that with following code:
public void getKeys(Set<String> keys,JSONObject obj,String path) {
Iterator<String> keys1 = obj.keys();
while(keys1.hasNext()) {
String key = keys1.next();
String currpath=path+'/'+key;
keys.add(currpath);
if (obj.get(key) instanceof JSONObject) {
getKeys(keys, obj.getJSONObject(key), currpath);
}
if (obj.get(key) instanceof JSONArray) {
JSONArray arr=(JSONArray) obj.get(key);
for(int i=0;i<arr.length();i++) {
JSONObject nobj=(JSONObject) arr.get(i);
getKeys(keys, nobj, currpath);
}
}
}
}
Upvotes: -1
Reputation: 3937
Maybe this is what you're looking for:
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]);
the result is:
glossary=/glossary
title=/glossary/title
GlossDiv=/glossary/GlossDiv
title=/glossary/GlossDiv/title
GlossList=/glossary/GlossDiv/GlossList
GlossEntry=/glossary/GlossDiv/GlossList/GlossEntry
ID=/glossary/GlossDiv/GlossList/GlossEntry/ID
SortAs=/glossary/GlossDiv/GlossList/GlossEntry/SortAs
...
Upvotes: 3