How to check if a nested path exists in json object for C#?

Viewed 5501
2 Answers

You can use SelectToken method from newtonsoft.json (token is null, when no match found):

    string json = @"
{
    ""car"": {
        ""type"": {
            ""sedan"": {
                ""make"": ""honda"",
                ""model"": ""civics""
            }
        },                
    }
}";

    JObject obj = JObject.Parse(json);
    JToken token = obj.SelectToken("car.type.sedan.make",errorWhenNoMatch:false);
    Console.WriteLine(token.Path + " -> " + token?.ToString());

I ended up using a extension method like so:

public static bool PathExists(this JObject obj, string path)
{
    var tokens = obj.SelectTokens(path);
    return tokens.Any();
}

But the spirit is the same as the accepted answer.

Related