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.

liang
  • 1,571
  • 1
  • 20
  • 22
  • before serialization or after ? need to parse json string or serialized object – Z.R.T. Sep 05 '18 at 05:34
  • possible duplicate https://stackoverflow.com/questions/7537398/how-to-use-c-sharp-example-using-jsonpath – Gauravsa Sep 05 '18 at 05:42
  • check out these two: 1. https://www.newtonsoft.com/json/help/html/QueryJsonSelectTokenJsonPath.htm . 2. https://stackoverflow.com/questions/19892617/get-path-of-json-value-using-json-net – NeverHopeless Sep 05 '18 at 05:49

2 Answers2

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());
Access Denied
  • 8,723
  • 4
  • 42
  • 72
  • this will also return null if the path exists but the value of the property is null or empty string – robs Aug 20 '20 at 05:09
  • 1
    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) – robs Aug 20 '20 at 05:46
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.

liang
  • 1,571
  • 1
  • 20
  • 22