7

say wanted to check if a path "L1.L2.L3" exists in a json object. There is a way to check the levels step by step (How to check whether json object has some property), but I wish to save the trouble, and check the path instead.

3

2 Answers 2

9

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());
Sign up to request clarification or add additional context in comments.

2 Comments

this will also return null if the path exists but the value of the property is null or empty string
If you need SelectToken to identify missing tokens when null is a possible value (such as "myProp" : "" or "myProp" : null) then you must set 'errorWhenNoMatch : true)
4

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.

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.