使用 Newtonsoft.Json.NET 搜索 JSON 根对象的正确 JsonPath 表达式是什么?

Ste*_*ath 6 json expression filter json.net jsonpath

大多数示例都涉及Stefan G\xc3\xb6ssner 的书店示例,但是我正在努力为简单对象(无数组)定义正确的 JsonPath 表达式:

\n\n
{ "Id": 1, "Name": "Test" }\n
Run Code Online (Sandbox Code Playgroud)\n\n

检查此 json 是否包含Id = 1.

\n\n

我尝试了以下表达式:$..?[(@.Id == 1]),但这确实使用 Json.NET 找到了任何匹配项?

\n\n

还尝试了Manatee.Json进行解析,似乎 jsonpath 表达式可能是这样的$[?($.Id == 1)]

\n

gre*_*nis 4

您发布的路径无效。我想你的意思是$..[?(@.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
Run Code Online (Sandbox Code Playgroud)

您只想直接导航该对象。使用$.Idwill 返回1,您可以在应用程序中验证它。

所有这些都说...

在我看来,您想要验证Id属性是1,而不是在数组中搜索该Id属性是的对象1。为此,您需要 JSON 架构,而不是 JSON 路径。

JSON Path 是一种查询语言,用于搜索满足特定条件的值(例如,其中Id == 1.

JSON 架构用于验证 JSON 是否满足某些要求(您的数据的形状正确)。用于验证对象是否具有值的 JSON 架构1可能类似于

{
  "properties": {
    "Id": {"const":1}
  }
}
Run Code Online (Sandbox Code Playgroud)

当然,这并不是很有用,因为它只会验证该Id属性是否为1,理想情况下,该属性应该只适用于一个对象。