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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With