C# JSON.Net parse and get list of all elements matching a value using LINQ

I'm having trouble finding the correct method for getting a list of json arrays from JObject.
_name element inside the array should be equal to foo.

This is the sample json:

{
    "doc": [{
        "bob": [{
            "tom": [{
                "frank": [{
                    "category": [{
                        "_name": "foo",
                        "letters": "abc"
                    },
                    {
                        "_name": "foo",
                        "letters": "def"
                    },
                    {
                        "_name": "foo",
                        "letters": "ghi"
                    },
                    {
                        "_name": "foo",
                        "letters": "jkl"
                    }]
                }]
            }]
        }]
    }]
}

And here's my code so far:

JObject o = JObject.Parse(File.ReadAllText(@"D:/Client/data.json"));

var results = from x in o["doc"].Children()
              where x["_name"].Value<string>() == "foo"
              select x;

I get this error:

"Value cannot be null.\r\nParameter name: source"

How do I get a list in which each element will be an array containing "_name" and "letters"?

Jon Skeet
people
quotationmark

Three problems:

  • You don't want the direct children of doc, you want the descendants.
  • You're using x["_name"].Value<string>() even if there is no _name property
  • You're using x["_name"].Value<string>() even on non-object children

These are all easily fixed though:

var doc = (JContainer) o["doc"];
var results = doc.Descendants()
                 .OfType<JObject>()
                 .Where(x => x["_name"] != null &&
                             x["_name"].Value<string>() == "foo");

people

See more on this question at Stackoverflow