0

I have a big nested JSON. I don't know the structure of the JSON. I just have a set of keys which are present in the JSON but I don't know where exactly in the JSON. How do I find out the path of a key from an unknown JSON structure assuming the key exists somewhere in it?

4 Answers 4

6

If your JSON structure is unknown, you can parse it into a JToken like this:

JToken token = JToken.Parse(json);

From there, you can use either SelectToken() or SelectTokens() with a recursive descent JsonPath expression to find the property (or properties) matching a key:

JToken match = token.SelectToken("$.." + keyToFind);

Once you have the matching token, you can get the path to it using its Path property:

string path = match?.Path;

Here is a working demo which assumes you have multiple keys to find and each key can appear multiple times in the JSON: https://dotnetfiddle.net/9Em9Iq

Sign up to request clarification or add additional context in comments.

Comments

0

For an unknown structure you can iterate over the objects :

var reader = new JsonTextReader(new StringReader(jsonText))
while (reader.Read())
    {
        // Do a condition on the variables reader.TokenType, reader.ValueType, reader.Value

    }

Comments

0

This method will log all paths in your top level json that have a key equal to "key"

        var keys = jobject.Properties().Where(p => p.Name == key).ToList();

        keys.ForEach(i => Console.WriteLine(i.Path));

This will NOT work in a recursive way but it is easy from this to do a recursive search from there

Comments

0

you can use

JObject o = JObject.Parse(<yourjson>);
dynamic obj = o.SelectTokens("$..Product");

Comments

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.