Search code examples
c#.netjsonjson.netjpath

Get the path of a key from nested JSON using Json.Net


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?


Solution

  • 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