简体   繁体   中英

How to use a string value in run time in SelectToken JSONPath query

I have the following code and I am using popular Newtonsoft library in C#

string json = {
  "students": [
    {
      "name": "student 1",
      "grades": [
        {
          "subject1": "A",
          "subject2": "B"
        }
      ]
    }
  ]
}

JObject rootJObject = JObject.Parse(json);

I want to pick a particular student object. If I query using JSONPath with literal string like below, I am getting the actual object

rootJObject.SelectToken("$.students[?(@.name=='student 1')]");

Now If I want to pass the query string in run time, like below

string studentName = "student 1"; rootJObject.SelectToken($"$.students[?(@.name=={studentName})]");

It's throwing an exception like "Unexpected character while parsing path query: s"

Is it a limitation that we can use literal string only with single quotes in JSONPath query and not a string value in run time?

As shown in Querying JSON with JSONPath , you need to put single quotes around string literals in filter expressions. So {studentName} should be '{studentName}' :

var result = rootJObject.SelectToken($"$.students[?(@.name=='{studentName}')]");

Or, using the old string.Format() style:

var result = rootJObject.SelectToken(string.Format("$.students[?(@.name=='{0}')]", studentName));

Or with simple string concatenations:

var result2 = rootJObject.SelectToken("$.students[?(@.name=='" + studentName + "')]");

Note that "string literal" does not mean "a string constructed entirely at compile time", it means "string value included in a JSONPath expression." Any c# string constructed by any method can be passed in. In each statement above a string is being constructed in run-time by surrounding the value of the studentName variable with single quotes and embedding it in a full JSONPath expression. The first statement uses string interpolation while the second uses an explicit function call, but both do the same thing.

Sample .Net fiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM