0

我在使用 JSONPath 做某事时遇到了一些麻烦。这就是我所拥有的:

[
    {
        "id": {
            "type": "literal",
            "value": "123456789",
            "datatype": "http://www.w3.org/2001/XMLSchema#string"
        },
        "name": {
            "type": "literal",
            "value": "John Doe",
            "datatype": "http://www.w3.org/2001/XMLSchema#string"
        }
    },
    {
        "id": {
            "type": "literal",
            "value": "2123456789",
            "datatype": "http://www.w3.org/2001/XMLSchema#string"
        },
        "name": {
             "type": "literal",
             "value": "Jane Doe",
             "datatype": "http://www.w3.org/2001/XMLSchema#string"
    }
}

] } ]

应用模式后我想得到的是:

[
    {
        "id": "123456789",
        "name": "John Doe"

     },
     {
        "id": "2123456789",
        "name": "Jane Doe"

     }
]

这可能吗?我正在做的最好的是["123456789", "John Doe","2123456789","Jane Doe"]

图案应该是什么样子?

4

1 回答 1

-1

使用 DefiantJS ( http://defianjs.com ),您可以使用 XPath 表达式查询 JSON 结构。DefiantJS 使用“搜索”方法扩展了全局对象 JSON,并将匹配项作为类似数组的对象返回。

这是一个示例代码;

var data = [
       {
          "id": {
             "type": "literal",
             "value": "123456789",
             "datatype": "http://www.w3.org/2001/XMLSchema#string"
          },
          "name": {
             "type": "literal",
             "value": "John Doe",
             "datatype": "http://www.w3.org/2001/XMLSchema#string"
          }
       },
       {
          "id": {
             "type": "literal",
             "value": "2123456789",
             "datatype": "http://www.w3.org/2001/XMLSchema#string"
          },
          "name": {
             "type": "literal",
             "value": "Jane Doe",
             "datatype": "http://www.w3.org/2001/XMLSchema#string"
          }
       }
    ],
    found = JSON.search(data, '//value'),
    str = '';

for (var i=0; i<found.length; i++) {
    str += found[i] +'<br/>';
}

document.getElementById('output').innerHTML = str;

要查看此代码的运行情况,请查看此小提琴;http://jsfiddle.net/hbi99/4BZMm/

有关更有用的 XPath 表达式,请参见此处的 XPath Evaluator;http://defiantjs.com/#xpath_evaluator

于 2014-05-18T23:12:33.710 回答