我在使用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"]
模式应该如何?
答案 0 :(得分:-1)
使用DefiantJS(http://defianjs.com),您可以使用XPath表达式查询JSON结构。 DefiantJS使用方法“search”扩展全局对象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