Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

c#

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.

like image 569
liang Avatar asked Sep 05 '18 05:09

liang


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());
like image 131
Access Denied Avatar answered Nov 05 '22 10:11

Access Denied


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.

like image 35
liang Avatar answered Nov 05 '22 09:11

liang