2

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"?

3
  • 1
    I meant "_name" not "_id", fixed Commented Aug 10, 2014 at 16:53
  • Is it really your intention to have doc.bob be an array containing an object with a property tom which has a property frank? Commented Aug 10, 2014 at 17:14
  • It's not mine JSON, it's from somewhere else. I simplified it. I get it as Json feed every couple of seconds. Commented Aug 10, 2014 at 17:22

1 Answer 1

5

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");
Sign up to request clarification or add additional context in comments.

1 Comment

Great, thank you. I must have misunderstood, because in documentation it says: "Returns a collection of child tokens of every array in the source collection." and I thought "child tokens of every array" will work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.