大多数示例处理 book store example from Stefan Gössner ,但是我正在努力为一个简单的对象(无数组)定义正确的 JsonPath 表达式:
{ "Id": 1, "Name": "Test" }
检查此 json 是否包含
Id = 1
.我尝试了以下表达式:
$..?[(@.Id == 1])
,但这确实找到了使用 Json.NET 的任何匹配项?也试过Manatee.Json用于解析,似乎 jsonpath 表达式可能类似于
$[?($.Id == 1)]
?
最佳答案
您发布的路径无效。我想你的意思是 $..[?(@.Id == 1)]
(有些字符乱序)。我的回答是这样假设的。
您使用的 JSON 路径表明您要查找的项目应该在一个数组中。
$ start
.. recursive search (1)
[ array item specification
?( item-based query
@.Id == 1 where the item is an object with an "Id" with value == 1 at the root
) end item-based query
] end array item specification
(1) the conditions following this could match a value no matter how deep in the hierarchy it exists
您只想直接导航对象。使用
$.Id
将返回 1
,您可以在应用程序中对其进行验证。所有这些都说...
在我看来,您想验证
Id
属性是 1
而不是在数组中搜索 Id
的对象属性是 1
.为此,您需要 JSON 架构,而不是 JSON 路径。JSON Path 是一种查询语言,用于搜索满足特定条件的值(例如,其中
Id == 1
的对象。JSON Schema用于验证 JSON 是否满足某些要求(您的数据形状正确)。用于验证您的对象是否具有值
1
的 JSON 模式可能是这样的{
"properties": {
"Id": {"const":1}
}
}
当然这不是很有用,因为它只会验证
Id
属性是 1
,理想情况下应该只对一个对象成立。
关于json - 使用 Newtonsoft.Json.NET 搜索 JSON 根对象的正确 JsonPath 表达式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49462187/