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:
console.writeline(json1["key2"]);
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
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)
{
...
}
If you want check key you can use:
if(json1["key1"].Type == JTokenType.Object)
{
if(json1["key1"].Value<JObject>().ContainsKey("key1_3"))
{
/// TODO
}
}
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