C#: JSONPath

Introduction

In this tutorial we will learn how to apply JSONPath expressions in C#, using the Json.net library.

JSONPath is a powerful query language for JSON, similar to XPath regarding XML. In our examples below, we will focus on how to apply simple expressions, as our focus will be on how to use the C# API exposed by the Json.net library.

How to apply JSONPath expressions

We will start our code by stating the namespaces we are going to use. We will use the System namespace, which allows us to print content to the console, and the Newtonsoft.Json.Linq namespace, which we will need to be able to query a JSON object using JSONPath.

using Newtonsoft.Json.Linq;
using System;

Moving on to the Main code, we will start by defining a string containing a JSON object that represents a person. It will have the following fields:

  • age: an integer representing the age of the person;
  • name: a string corresponding to the name of the person;
  • languages: an array of strings representing the languages that the person speaks;
  • address: an object containing the address of the person, which is composed by the city and the street (both will be strings).

Now that we have our JSON string, we will parse it to a JObject. To do so, we simply need to call the static Parse method, also from the JObject class. As input, this method receives the string we want to parse and, as output, it returns the corresponding JObject instance.

for a detailed tutorial on how to parse JSON in C#, please check this previous tutorial.

JObject obj = JObject.Parse(person);

To apply JSONPath expressions we can use the SelectToken method. As input of this method we need to pass a string with the JSONPath expression we want to use and, as output, it will return a JToken with the result (or null, in case nothing is found).

So, we will start by using very simple JSONPath expressions to get the properties at the root of the object. The syntax is the following:

$.propertyName

You can check the JSONPath syntax in more detail here. In short, $ represents the root object and .propertyName allows to select the specified property in a parent object. So, we will use 4 of these expressions to get the age, the name, the languages array and the address objec.

JToken age = obj.SelectToken("$.age");
JToken name = obj.SelectToken("$.name");
JToken languages = obj.SelectToken("$.languages");
JToken address = obj.SelectToken("$.address");

We will then print all the 4 JTokens we have obtained, to confirm they contain the values we expect.

Console.WriteLine(age);
Console.WriteLine(name);
Console.WriteLine(languages);
Console.WriteLine(address);

To finalize this code sample, we will now try to obtain the two properties contained in the address object and print their values to the console. The JSONpath expressions needed are shown in the snippet below.

JToken city = obj.SelectToken("$.address.city");
JToken street = obj.SelectToken("$.address.street");

Console.WriteLine(city);
Console.WriteLine(street);

The complete C# code can be seen below.

namespace JsonPath
{
    using Newtonsoft.Json.Linq;
    using System;

    class Program
    {
        static void Main()
        {

            var person = @"
                {
                    ""age"": 20,
                    ""name"": ""Jake"",
                    ""languages"":[""pt-pt"", ""en-us""],
                    ""address"": {
                        ""city"": ""Lisbon"",
                        ""street"":""Road street""
                    },                                            
                 }
            ";

            JObject obj = JObject.Parse(person);

            JToken age = obj.SelectToken("$.age");
            JToken name = obj.SelectToken("$.name");
            JToken languages = obj.SelectToken("$.languages");
            JToken address = obj.SelectToken("$.address");

            Console.WriteLine(age);
            Console.WriteLine(name);
            Console.WriteLine(languages);
            Console.WriteLine(address);


            JToken city = obj.SelectToken("$.address.city");
            JToken street = obj.SelectToken("$.address.street");

            Console.WriteLine(city);
            Console.WriteLine(street);

        }
    }
}

Testing the code

To test the previous code, simply compile it and run it in a tool of your choice. In my case, I’ll be using Microsoft’s Visual Studio 2019.

Upon running the code, you should get a result similar to figure 1. The first 4 JTokens printed to the console show the age, the name, the languages array and the address object, as expected. The last two lines printed to the console correspond to the city and address, also as we defined in our code.

Output of the JSONPath expressions, printed to the console.
Figure 1 – Output of the JSONPath expressions.

Suggested C# readings

Leave a Reply

%d bloggers like this: