0

I am listing down my sample JSON below, I want to write a JSONPath that selects element when subjects has (or contains) "Maths".

NOTE: I am using Goessner's JSONPath using Newtonsoft library (C#)**

{
   "class":{
      "type":"group",
      "identifier":"MyFavClass",
      "subs":[
         {
            "type":"individual",
            "identifier":"Rambo"
         },
         {
            "type":"individual",
            "identifier":"Rancho"
         },
         {
            "type":"biggroup",
            "identifier":"village",
            "subjects":[
               "Maths",
               "English"
            ]
         },
         {
            "type":"biggroup",
            "identifier":"newvillage",
            "subjects":[
               "Maths"
            ]
         }
      ]
   }
}
1
  • 1
    1) What have you tried? 2) I want to write a JSONPath that selects element when subjects has (or contains) "Maths". - what elements do you want to select, exactly? Are they the elements of the "class.subs[*].subjects[*]" array, or the container "class.subs[*]" array? Commented Dec 31, 2020 at 5:37

1 Answer 1

1

Assuming you are using Json.NET's SelectTokens() method for your JSONPath queries, you may find all math subjects using the following query:

var value = "Maths";

var subjects = root.SelectTokens($"class.subs[*].subjects[?(@ == '{value}')]");

Of course this will just return a sequence of JValue tokens with value "Maths". If you want the class.subs[*] objects whose subjects[*] arrays contains "Maths", you may do:

var subs = root.SelectTokens($"class.subs[?(@.subjects[?(@ == '{value}')])]");

Notes:

  • [?(...)] applies a filter expression ... to an array.

  • In a filter expression, array contents that are primitive values may be matched using the @ symbol for the current object.

  • Json.NET's implementation of JSONPath supports nested queries inside array filter expressions. Thus [?(@.subjects[?(@ == '{value}')])] matches array items that have an item in their "subjects" array that matches the value parameter.

  • Note that search values that contain a single quote character ' must be escaped as shown in Querying JSON with JSON Path and escaped properties. Thus if the string to be matched was Math's you would need to escape it like so:

    var value = "Math's".Replace("'", "\\\'");
    

Demo fiddle here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.