A guide on using JSONPath to parse a JSON object and filter based on a specific string value within an array nested inside the

Below is a sample JSON that I have listed down. I am looking to create a JSONPath that selects elements where the subject includes "Maths".

Please note that I am utilizing Goessner's JSONPath with the Newtonsoft library in 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"
            ]
         }
      ]
   }
}

Answer №1

If you are utilizing the SelectTokens() method in Json.NET for your JSONPath searches, you can locate all math subjects with this query:

var value = "Maths";

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

This will return a sequence of JValue tokens containing the value "Maths". If you want the class.subs[*] objects that have "Maths" in their subjects[*] arrays, do this:

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

Some important notes to consider:

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

  • In filter expressions, primitive values within arrays can be identified using the @ symbol representing the current object.

  • Json.NET's JSONPath implementation allows nested queries inside array filter expressions. Hence,

    [?(@.subjects[?(@ == '{value}')])]
    selects array elements with items in their "subjects" array matching the specified value.

  • Please note that if your search value includes a single quote ', it must be escaped as demonstrated in Querying JSON with JSON Path and escaped properties. For example, to match Math's, escape it like this:

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

Check out the demonstration fiddle here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to transfer my json file to the server?

How do I send a json file to the server using Flutter? { "likes":{ "job_name":"teh", "job_address":"teh" } , "equals":null } Upon trying to implement this, I enco ...

Utilizing nested dynamic attributes as grid columns within ExtJS applications

I recently experimented with the dynamic attributes approach in my prototype mongoDB application. This approach essentially structures data like this: { SKU: "Y32944EW", type: "shoes", attr: [ { "k": "manufacturer", "v": "ShoesForAll ...

Python does not support serialization of JSON data

Having a collection of objects in the specific structure shown below, I aimed to store it in a json file. {'result': [{'topleft': {'y': 103, 'x': 187}, 'confidence': 0.833129, 'bottomright': {&ap ...

Updating subdata in an array using Reactjs handleChange

I am facing an issue with my handleChange function. While I can easily change data in the same directory without any problem, I'm struggling to update sub-data. I would like to find a clean solution for this without having to add extra functions withi ...

What is the process for updating JSON using TextFields?

I am currently facing an issue with my TextFields displayed within a material-ui dialog. These TextFields are initially populated by JSON data, which you can see in the example below. The problem is that once the TextFields are populated, I am unable to up ...

The angular.json file contains a script and a styles property

After encountering issues with adding styles and scripts to my angular.json file, I discovered that neither Bootstrap nor other scripts were taking effect. It turns out there are two places where you can define scripts and styles in the angular.json file a ...

Dealing with eliminating the white space from key values in Android Retrofit proved to be a challenge for me

Having trouble posting a value via JSON to Retrofit as it's including spaces in the format, preventing me from receiving a success response in Android. Retrofit retrofit = new Retrofit.Builder() .baseUrl(activity.getResources( ...

Converting an array from JSON Schema into OWL ontology

My current challenge involves the mapping of an array defined in JSON Schema to OWL 2. Here is a basic example of a JSON Schema: { "properties": { "nm_prop": { "type": "array", "items": {"type": "number"} } } } The r ...

Retrieving data from a JSON object stored within a database column

There is a dataframe presented below: +-------+-------------------------------- |__key__|______value____________________| | 1 | {"name":"John", "age": 34} | | 2 | {"name":"Rose", "age" ...

Retrieving the JSON data from an API using Laravel

Currently, I am experimenting with APIs and my latest project involves utilizing the Google Directions API within my application. To handle this, I have created a form to collect user input and generate the necessary URI directly in the routes.php file: ...

A guide on successfully transferring JSON Data to an Express REST API

Currently, I am in the process of developing a REST API with Node/Express and have a query regarding the setup of the API along with integrating a JSON file. As an illustration, the JSON data that I wish to reference consists of an ID number, model, and co ...

What is the best way to capture the output of a script from an external website using Javascript when it is returning simple text?

Recently, I decided to incorporate an external script into my project. The script in question is as follows: <script type="application/javascript" src="https://api.ipify.org"> </script> This script is designed to provide the client's IP ...

Unraveling JSON data in AngularJS

After receiving a response from an OData service in JSON format, the data looks like this: [ { "id":1, "ProductName":"Surface Pro 2" }, { "id":2, "ProductName":"iPad" }, ] When att ...

How can you show a different value in a select menu with AngularJS on selection?

When designing my menu to display US States for selection, I wanted to show both the 2-letter state code and the full name of the state initially. However, once the user selects a state, I only want to display the 2-letter code. This is how my menu looks: ...

Guide on utilizing PHP to display a particular value from a JSON file

Hello, I am trying to extract specific data from a JSON response. Here is the structure of the JSON: { "data":{ "user_quota":[ { "group_limit":10240, "quota":0, "support_share_quota":false, ...

Retrieve data from an array and insert it into a SQL database by matching the array element with

Currently, I am attempting to send a JSON payload to SQL in order to import a specific column. Within the JSON data, there is a segment structured like this: "Custom":[ {"id":100, "value" 8 }, {"id":200, ...

Position of JSON data response is inaccurate

Currently, I have a function that calls an API from the server in the following manner: getDataSet(callback) { request.open('POST', `${apiPath}`); request.setRequestHeader('Content-Type', 'application/x-ww ...

Storing configuration on shared hosting: a guide to PHP

Imagine having a shared host scenario with the web root in /home/username/www/. Here I have a PHP application that relies on a configuration file located at /home/username/www/include/config.json. This important file includes passwords and critical configu ...

Transform the JSON data into a collection of unique objects in a Flutter application

Currently, I am working on saving and retrieving a list of custom objects to and from shared preferences. Below is the code for my save function: save(String key, value) async { final prefs = await SharedPreferences.getInstance(); prefs.setString(key, j ...

Instructions for selecting all checkboxes in an HTML table with just one click

Developing an aspx page with 3 HTML tables, I am dynamically adding checkboxes to each cell. Additionally, I have a checkbox outside each table. When I check this checkbox, I want all checkboxes in the corresponding HTML table to be checked. However, curre ...