获取JSON对象的子键名

时间:2013-05-30 10:51:42

标签: javascript json node.js xpath key

我需要获取json(即)的xpath基本上我需要获取jsons的密钥及其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' ]

我需要所有的钥匙以及路径。我被困在这里。任何解决方案都会有所帮助

2 个答案:

答案 0 :(得分:3)

也许这就是你要找的东西:

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

...

答案 1 :(得分:-1)

您可以使用以下代码进行操作:

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);
            }
        }
    }
}