jpaull
jpaull

Reputation: 278

Find items in JArray by name/key

I have JSON that looks similar to this:

[{“itemA”:{“name”:”foo”,”other”:"bar”}},{“itemB”:{“name”:”foo2”,”other”:”bar2”}},{“itemC”:{“name”:”foo3”,”other”:”bar3”}},{“itemB”:{“name”:”foo4”,”other”:”bar4”}}]

I have parsed it into a JArray object, but now I need to find specific objects in that array by name (i.e. "itemB"). I can't seem to find how to do this when the array is the root object.

I have tried the code below, but I only get back a null JToken.

JArray array = JArray.Parse(json);
JToken itemATkn = array.SelectToken("itemA");

I also need to be able to find multiple values (i.e. both "itemB" items in example above).

Upvotes: 3

Views: 6510

Answers (1)

Chihuahua Enthusiast
Chihuahua Enthusiast

Reputation: 1580

Try this:

JArray array = JArray.Parse(json);
if (array.Count > 0) {
    JToken itemATkn = array[0]["itemA"];
}

Upvotes: 4

Related Questions