4

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

0

2 Answers 2

12

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

Comments

6

If you want check key you can use:

if(json1["key1"].Type == JTokenType.Object)
{
    if(json1["key1"].Value<JObject>().ContainsKey("key1_3"))
    {
        /// TODO
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.