0

Basically I'm doing some webscraping using HTMLAgilityPack and I'm getting a huge json as a string, which I then convert into a JObjectusing the json.net package.

Now somewhere deeply within said JObject there are some objects I want. But since it is very deeply nested, I wanted to know if there is actually a way to get to those objects, not knowing where exactly within the JObject they are. All I know is their name. Is there any way for me to do some kind of search within the whole JObject, just knowing the object/property names I'm looking for?

Sadly I wasn't able to find any related questions/documented methods I could make use of.

Lesic
  • 136
  • 12
  • 1
    You can write a DFS, or use `.Descendants()`. – SLaks Dec 08 '17 at 15:08
  • Write a method with recursion, to continually iterate through each layer of the object till you find your value. Obviously, a model to represent the data and utilizing that, would be far easier. Visual Studio even has a "Paste Special" to create a class built off JSON. – Greg Dec 08 '17 at 15:13
  • You can iterate through unknown json manually using `.Children()`, see [this answer](https://stackoverflow.com/a/8856084/1997232). – Sinatr Dec 08 '17 at 15:13
  • in adition to @Sinatr answer you can use `.Childeren()` in a method using recursion. that way you can cycle to their childeren too in case that they have any. – Arno Dec 08 '17 at 15:20
  • You can either use `SelectTokens()` with a suitable JSONPath expression as shown in [How do I get a deeply-nested property from JSON string?](https://stackoverflow.com/q/36324494/10263), or use a recursive method as shown in [Searching for a specific JToken by name in a JObject hierarchy](https://stackoverflow.com/q/19645501/10263) – Brian Rogers Dec 08 '17 at 18:13

1 Answers1

1

This might work for you:

private JToken GetValueByKey(JObject jObject, string key)
{
    foreach (KeyValuePair<string, JToken> jProperty in jObject)
    {
        if (jProperty.Key.Equals(key))
        {
            return jProperty.Value;
        }
        else if (jProperty.Value is JObject)
        {
            return GetValueByKey((JObject)jProperty.Value, key);
        }
    }
    return null;
}

It takes the JObject you want to search for a key in. and the key you want to search for. It maps all the properties in the JObject to see or it matches the key, if it doesn't it will check or the current property can be cast to a JObject. in case it can be cast to a JObject it will check for all that JObjects values or your key matches.

if a match is found it will return the Value matching your key.

if no match is found after cycling through all properties in your JObject it will return null.

Arno
  • 185
  • 2
  • 13