Home > other >  How do I select an array element in a JArray when the array is on the root?
How do I select an array element in a JArray when the array is on the root?

Time:12-21

Using JSON.NET, I would like to search a JSON array for an element containing a key value and get the ID from that element. So for the JSON below, I want to search on Url == "https://www.google.com/" and get the value for ID.

{
  [
    {
      "Url": "https://www.google.com/",
      "Type": "SEARCH",
      "ID": 1
    },
  .
  .
  .
    {
      "Url": "https://www.someurl.com/",
      "Type": "TYPE",
      "ID": 100
    }
  ]
}

The JArray class includes the SelectToken method, but this requires a key parameter. Can I select an element off the root as above using JArray with lambda notation?

CodePudding user response:

Well, assuming you have a valid JSON array. All you need to apply is. JArray.Parse and then basic linq will do it.

    var sourceJson = @"
        [
    {
      ""Url"": ""https://www.google.com/"",
      ""Type"": ""SEARCH"",
      ""ID"": 1
    }, 
    {
      ""Url"": ""https://www.someurl.com/"",
      ""Type"": ""TYPE"",
      ""ID"": 100
    }
  ]
  ";
        var parsed = JArray.Parse(sourceJson);
        var goog = parsed.FirstOrDefault(r => r["Url"].Value<string>() == "https://www.google.com/");
        goog.ToString().Dump();

Fiddle

CodePudding user response:

fix your json for the start by removing extra "{ }"

var json="{[{... your json ";
json= json.Substring(1,json.Length-2);

you can make search using 2 ways

1.Deserialize json

var items= JsonConvert.DeserializeObject<List<Item>>(json);

var itemId=items.FirstOrDefault(i => i.Url== @"https://www.google.com/" ).ID;
  1. Parse json
var jItems=JArray.Parse(json);
var jItemId=jItems.FirstOrDefault(i => (string) i["Url"]== @"https://www.google.com/" )["ID"];

classes to deserialize

public class Item
{
    public string Url { get; set; }
    public string Type { get; set; }
    public int ID { get; set; }
}
  • Related