1

Given some 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"
    }
  ]
}

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

{
  "type"  : "Bill's Automotive",
  "number": "0123-4567-8888"
}

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

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

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

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?

Ian Boyd
  • 246,734
  • 253
  • 869
  • 1,219

3 Answers3

5

You need to provide backslash-escaped quote to the query:

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

Note that you need single quotes to wrap search term and \\ so final string actually contains \'.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
0

I don't know how to do it with SelectToken, but See Alexei's answer for escaping the quote, but you can do it with some LINQ.

 var billsPhone = o["phoneNumbers"]
                  .FirstOrDefault(t => t["type"].Value<string>() == "Bill's Automotive");
tymtam
  • 31,798
  • 8
  • 86
  • 126
-1

Use a verbatim string

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

What is the difference between a regular string and a verbatim string?

Can I escape a double quote in a verbatim string literal?

live627
  • 397
  • 4
  • 18
  • What version of Newtonsoft Json.Net you are using? The code you shown does not seem to work with current (12.x) one claiming `"` is unexpected... I mean it indeed compile unlike sample shown in the question... But does not work earlier than OP said - so most likely code in the question is not 100% one OP tried (but close enough). – Alexei Levenkov Oct 21 '19 at 22:46