Search code examples
c#jsonjson.net

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


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?


Solution

  • 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