3

I have the folowing if statement which works fine:

if (json1.ContainsKey("key2"))
{
    // do something here.
}

json1 contains the following:

{
  "key1": {
    "key1_1": "value1_1",
    "key1_2": "value1_2",
    "key1_3": [
      "value1_3_2",
      "value1_3_2"
    ],
    "key1_1": "value1_1"
  },
  "key2": "value2_1",
  "key3": "value3_1"
}

I can get specific values from the keys like this:

  1. console.writeline(json1["key2"]);

  2. console.writeline(json1["key1"]["key1_3"][0]);

I am now trying to check if key1_3 exists, but don't know how to.

I have tried the following code examples and they do not work:

if (json1.ContainsKey("key1_3"))
{
    // do something here.
}

if (json1["key1"].ContainsKey("key1_3"))
{
    // do something here.
}

How do I check if a nested key exists such as key1_3

oshirowanen
  • 15,297
  • 82
  • 198
  • 350

2 Answers2

9

ContainsKey is method defined on JObject while indexer returns JToken. You can use json path, SelectToken and check it for null:

var token = json1.SelectToken("$.key1.key1_3");
if(token != null)  
{
    ....
}

Or like this:

if(json1["key1"]?["key1_3"] != null)
{
    ...
}
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
4

If you want check key you can use:

if(json1["key1"].Type == JTokenType.Object)
{
    if(json1["key1"].Value<JObject>().ContainsKey("key1_3"))
    {
        /// TODO
    }
}
progpow
  • 1,560
  • 13
  • 26