0

我需要获取 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' ]

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

4

2 回答 2

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=/glossary/GlossDiv/GlossList

GlossEntry=/glossary/GlossDiv/GlossList/GlossEntry

ID=/glossary/GlossDiv/GlossList/GlossEntry/ID

SortAs=/glossary/GlossDiv/GlossList/GlossEntry/SortAs

...

于 2013-05-30T13:20:39.747 回答
-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);
            }
        }
    }
}
于 2018-11-29T10:40:25.390 回答