Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using LINQ in JArray

I have a JSON

{
  "departments": [
    {
      "2": {"city": "Petersburg", "employees": "1200"}
    },
    {
      "1": {"city": "Ekaterinburg", "employees": "4000"}
    }
  ]
}

How can I get the value of the city, if I know an ID using LINQ or something else?

I tried

var id = 2;
json["departments"].Single(x=>x.Name==id.ToString())["city"];

But it doesn't work, I get a compilation error:

'JToken' does not contain a definition for 'Name' and no accessible extension method 'Name' accepting a first argument of type 'JToken' could be found (are you missing a using directive or an assembly reference?)

Demo fiddle here.

like image 234
Иван Брайко Avatar asked Mar 02 '21 19:03

Иван Брайко


People also ask

How to use LINQ in JSON?

The simplest way to get a value from LINQ to JSON is to use the Item[Object] index on JObject/JArray and then cast the returned JValue to the type you want. JObject/JArray can also be queried using LINQ.

What is LINQ used for in C#?

LINQ (Language Integrated Query) is uniform query syntax in C# and VB.NET to retrieve data from different sources and formats. It is integrated in C# or VB, thereby eliminating the mismatch between programming languages and databases, as well as providing a single querying interface for different types of data sources.

How do I convert JArray to JObject?

it is easy, JArray myarray = new JArray(); JObject myobj = new JObject(); // myobj.

What is JObject and JToken?

The JToken hierarchy looks like this: JToken - abstract base class JContainer - abstract base class of JTokens that can contain other JTokens JArray - represents a JSON array (contains an ordered list of JTokens) JObject - represents a JSON object (contains a collection of JProperties) JProperty - represents a JSON ...


1 Answers

Your LINQ query can be implemented as follows:

var id = "2";
var city = (string)json["departments"]
    .Where(o => o[id] != null) // From the departments array, select the object where the required id property exists
    .Select(o => o[id]["city"]).SingleOrDefault(); // An extract the value of "city" from the nested object.

Or, equivalently:

var id = "2";
var city = (string)json["departments"]
    .SelectMany(i => i) // Use SelectMany() to project the properties of the array items to a flat enumerable 
    .Cast<JProperty>()  // Cast them to JProperty
    .Where(p => p.Name == id) // Now you can use Name
    .Select(p => p.Value["city"])
    .SingleOrDefault();

Alternatively, you could use SelectToken() for this purpose:

var id = "2";
var path = $"departments[*].{id}.city"; // departments[*].2.city
var city = (string)json.SelectToken(path);

SelectToken() supports JSONPath syntax, and [*] is the JSONPath wildcard operator indicating that all array items should be searched.

Demo fiddle here.

like image 52
dbc Avatar answered Oct 21 '22 09:10

dbc