JSON - Querying JSON with SelectTokens.cs

CSharp · Console

/Program.cs

// https://www.newtonsoft.com/json/help/html/SelectToken.htm

using System;
using System.Collections.Generic;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public class Program
{
	public static void Main()
	{
		Console.WriteLine(JsonConvert.SerializeObject(o.SelectTokens("$..Products[0].Name"), Formatting.Indented));
		Console.WriteLine(JsonConvert.SerializeObject(o.SelectTokens("$..Products[?(@.Price == 50)].Name"), Formatting.Indented));
		Console.WriteLine(JsonConvert.SerializeObject(o.SelectTokens("$..Products[?(@.Price >= 50)].Name"), Formatting.Indented));
	}
	
	
	public static 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
        }
      ]
    }
  ]
}");
}
;