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?
Asked
Active
Viewed 2,791 times
4 Answers
4
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

Brian Rogers
- 125,747
- 31
- 299
- 300
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
}

lagripe
- 766
- 6
- 18
0
you can use
JObject o = JObject.Parse(<yourjson>);
dynamic obj = o.SelectTokens("$..Product");

Derviş Kayımbaşıoğlu
- 28,492
- 4
- 50
- 72
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

Rakiah
- 240
- 2
- 15