如何处理过滤器表达式中的撇号?

Ian*_*oyd 1 c# json.net jsonpath

鉴于一些json:

{
  "firstName": "John",
  "lastName" : "doe",
  "age"      : 26,
  "address"  : {
    "streetAddress": "naist street",
    "city"         : "Nara",
    "postalCode"   : "630-0192"
  },
  "phoneNumbers": [
    {
      "type"  : "Bill's Automotive",
      "number": "0123-4567-8888"
    },
    {
      "type"  : "home",
      "number": "0123-4567-8910"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

I want to return the Bill's Automotive phone number object:

{
  "type"  : "Bill's Automotive",
  "number": "0123-4567-8888"
}
Run Code Online (Sandbox Code Playgroud)

Using Json.NET, which uses the jsonpath syntax, i have the filter expression:

phoneNumbers.[?(@.type=="Bill's Automotive")]
Run Code Online (Sandbox Code Playgroud)

And this works fine when you test it on:

where you can try this for yourself.

But fails in Json.net

But in C#, at runtime, using Newtonsoft Json.Net, the code throws an exception:

JToken billsPhone= o.SelectToken("phoneNumbers.[?(@.type=="Bill's Automotive")]");

Newtonsoft.Json.JsonException: Unexpected character while parsing path query: s
Run Code Online (Sandbox Code Playgroud)

Obviously it sees the apostrophe, and thinks its the end of the query string.

Other variations i have tried

  • phoneNumbers.[?(@.type=="Bill's Automotive")]
  • phoneNumbers.[?(@.type=="Bill\'s Automotive")]
  • phoneNumbers.[?(@.type=="Bill''s Automotive")]
  • phoneNumbers.[?(@.type=="Bill\u0027s Automotive")]

So i give up.

How do you filter json in Newtonsoft Json.NET?

Ale*_*kov 5

您需要为查询提供反斜杠转义的引号:

JToken billsPhone = o.SelectToken("phoneNumbers.[?(@.type=='Bill\\'s Automotive')]");
Run Code Online (Sandbox Code Playgroud)

请注意,您需要单引号来包装搜索词,\\因此最终字符串实际上包含\'.