Click or drag to resize
Json.NET

Querying JSON with SelectToken and LINQ

 

This sample loads JSON and then queries values from it using a combination of SelectToken(String) and LINQ operators.

Sample
Usage
JObject o = JObject.Parse(@"{
  'Stores': [
    'Lambton Quay',
    'Willis Street'
  ],
  'Manufacturers': [
    {
      'Name': 'Acme Co',
      'Products': [
        {
          'Name': 'Anvil',
          'Price': 50
        }
      ]
    },
    {
      'Name': 'Contoso',
      'Products': [
        {
          'Name': 'Elbow Grease',
          'Price': 99.95
        },
        {
          'Name': 'Headlight Fluid',
          'Price': 4
        }
      ]
    }
  ]
}");

string[] storeNames = o.SelectToken("Stores").Select(s => (string)s).ToArray();

Console.WriteLine(string.Join(", ", storeNames));
// Lambton Quay, Willis Street

string[] firstProductNames = o["Manufacturers"].Select(m => (string)m.SelectToken("Products[1].Name"))
    .Where(n => n != null).ToArray();

Console.WriteLine(string.Join(", ", firstProductNames));
// Headlight Fluid

decimal totalPrice = o["Manufacturers"].Sum(m => (decimal)m.SelectToken("Products[0].Price"));

Console.WriteLine(totalPrice);
// 149.95