Json.NET - Finding an element in a JArray Object

Recently I hit a roadblock in parsing and finding an element in a JArray object in one of the projects which I was working at my workplace. I was working with JSON string like the one given below.

"[{'Name':'Amal', 'Country':'India'},{'Name':'Luke', 'Country':'England'},{'Name':'Tom', 'Country':'Australia'}, {'Name':'Ram', 'Country':'India'}]"

It was an array of items which has got two keys named Name and Country and I want to return the object if the search criteria is matched. I can use the combination of a foreach loop and condition check to retrieve the item, but I didn't want to use that because I felt that it's not the proper way to do it. Also, I didn't wanted to create a new class to bind these elements because I just needed to find whether this string has value for a particular key and return the object if found. So I did some research on this topic and finally resolved it using the SelectToken method available in JSON.NET.

First you need to add the JSON.NET package to your project via NuGet. Then import the Newtonsoft.Json.Linq namespace to your class using the below statement.

using Newtonsoft.Json.Linq;

Next up is to parse the json string to an array using the JArray.Parse() method.

var jArrObject = JArray.Parse(<JSON string>);

Now we will make use of the JSONPath queries to search for the item 

var srchItem = jArrObject.SelectToken("$.[?(@.<key name>=='<value>')]");

If you search result is going to have more than one values then you need to make use of the SelectTokens() method.

var items = jArrObject.SelectTokens("$.[?(@.<key name>=='<value>')]");

In JSONPath syntax,

$ -> root element

.  -> child operator

[] -> subscript operator

?() -> used to apply a filter

So in our case the expression is equivalent to saying that For all($) elements in the string return the item if the current element(@) is matching the specified filter(<key name>=='<value>').

You can refer the documentation here to know more about the JSONPath syntax.


No Comments

Add a Comment