Filter JSON by key name using LINQ

2.8k views Asked by At

Given the following JSON:

{
    "items": {
        "primary": "structured",
        "item0": {
            "keyA1": "value1",
            "keyA2": "value2",
            "keyA3": "value3"
        },
        "item1": {
            "keyB1": "value1",
            "keyB2": "value2",
            "keyB3": "value3"
        },
        "item2": {
            "keyC1": "value1",
            "keyC2": "value2",
            "keyC3": "value3"
        }
    }
}

Is it possible to get only those objects whose keys start with "item", i.e. "item0", "item1", and "item2"? Preferably with Json.NET and/or LINQ, but JSONPath expression would also be fine (I tried using asterisks in JSONPath expression to match item*, but it did not work).

1

There are 1 answers

3
Brian Rogers On BEST ANSWER

Sure, you can do this with Json.Net's LINQ-to-JSON API:

var items = JObject.Parse(json)["items"]
                   .Children<JProperty>()
                   .Where(jp => jp.Name.StartsWith("item"))
                   .Select(jp => (JObject)jp.Value)
                   .ToList();

foreach (var item in items)
{
    foreach (var kvp in item)
    {
        Console.WriteLine(kvp.Key + ": " + kvp.Value);
    }
    Console.WriteLine();
}

Fiddle: https://dotnetfiddle.net/j6nn3P