我从 REST 服务调用获得 JSON 响应,并且只想从响应中选择一些字段。我正在使用 JSONPath 来过滤字段。下面是 JSON 示例:
{
"store": {
"book": [{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{
"category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}],
"bicycle": {
"color": "red",
"price": 19.95
}
}
}
Run Code Online (Sandbox Code Playgroud)
例如,我想从类别为“参考”的响应中选择作者和标题。我正在使用下面的 JSONPath
$.store.book[?(@.category='reference')]
Run Code Online (Sandbox Code Playgroud)
这给了我以下回应:
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
}
Run Code Online (Sandbox Code Playgroud)
但是,我不想要所有字段。我只想要作者和标题。如果我尝试$.store.book[?(@.category='reference')]['author']
,它会给我作者姓名但如果我尝试$.store.book[?(@.category='reference')]['author', 'title']
,它不会返回任何内容。
JSONPath 中是否有任何条款可以选择(或排除)有条件或无条件的字段?
我正在使用http://jsonpath.curiousconcept.com/来测试 JSONPath。
提前致谢。
您的帖子没有说明您使用的是 Goessner 还是 Flow Communications JSON Path 表达式评估器。两者都可以在您使用的表达式测试器站点上找到。如果您使用的是 Goessner,则以下查询有效,但在您使用的表达式测试站点上无效
$.store.book[?(@.category=='reference')]['author','title']
Run Code Online (Sandbox Code Playgroud)
请注意双等号 ( @.category=='reference'
) 而不是单个等号。此外,选择字段的逗号后不应有空格'author','title'
。
你可以看到这里的表达式 http://www.jsonquerytool.com/sample/jsonpathselectmultiplefields
如果你尝试这样做会怎样:
$.store.book[?(@.category='reference')]['author']['title']
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6746 次 |
最近记录: |