Skip to main content

Introduction to Using LINQ with JSON Objects

Language Integrated Queries

Ossi Galkin avatar
Written by Ossi Galkin
Updated over a year ago

Using LINQ with JSON Objects

Language Integrated Query (LINQ) is a method to query data using familiar syntax from query languages, such as SQL. You can use LINQ to query lists or arrays to find data matching rules or patterns you want. In addition to iterable data types, you can also use LINQ to query data in JObject.

Lets take the example from previous module where we created new JArray from input JSON dynamically using Dictionary. Lets say that we only want to map data of people who are younger than 40. We can implement this rule using LINQ. What we need to do first is to strongly type the original JArray as an object of JArray. In Frends, all variables defined in C# Expression or C# Statement Elements are dynamically typed. This means we do not know what kind of data is stored in the variable during compilation. To use LINQ to query data in JArray we need to explicitly define the variable containing the JArray as JArray. This can be done by defining variable type in C# Expression Element.

We can then modify the Foreach-iteration from the example in last module, where we wanted to iterate the JArray. This time we only want to map people who are under 40 years old. We can do this with the following query:

Lets split this query into smaller pieces. From-keyword defines that we want to find data from "#var.jsonArray", which in this case is a JArray. We define a variable named "people", which will be a single data entry in the JArray. This variable will be strongly typed as JToken, which is a parent class for JArray and JObject. Where-keyword defines the rule which will filter the desired data from the JArray. In this rule we have defined that we want to find people from the JArray who's age is less than 40. Since "people"-variable is strongly typed as JToken, we cannot use dot notation to access Age-property, but we need to use JToken's bracket syntax. Looking at the documentation we can see that JToken's bracket syntax returns the value in the key as JToken, so we cannot compare the value against an integer. Hence, we need to cast the JToken into an integer. Lastly, select-keyword defines what we want to return from the query. In this case we want to return the whole value stored in "people"-variable. LINQ will always return an iterable object, so we are always able to iterate the result of the query through even if the query finds only one or no entries. Below is the result of data mapping, which is done same way as in the example in the previous module.

From the result we can see that Susan Example is not part of mapped JArray since she is 40 years old. LINQ has filtered her out of the original JArray due to the rule which we defined in the query.

Did this answer your question?