How to Check if A JSON Object Contains A Certain Key?

activities

#1

Hello, I want to validate a JSON formatted text file used for external config file.
The result is a JSON Object data type (Newtonsoft one).
How do I check if some key exists in the JSON?
Something like config.hasKey(“parameterFolder”)?
( I feel like letting it throw exception and let Try Catch cleans it betrays the use of Try Catch)


#2

Hey @whyyouandi

Have you gone through with this existing thread? -

Let me know if you are facing any problem with this.

Regards…!!
Aksh


#3

Hello @aksh1yadav, thank you for your response.
I checked your link, but what I wanted was to check beforehand if the key itself exists.

Like in the sample, we can get the id by
json_data.GetValue(“id”).ToString or
json_data(“id”).ToString but not for
json_data(“memo”).ToString (since it is, not exists in the JSON data).
Is there anyway to check it before hand? If the JSON data contains key named “memo”, do this…?

Modified exampled attached.
Jason_http_sample_without_json_array.xaml (7.2 KB)


#4

Well u can use the same thing in if condition and check it is coming empty or is equal to null based on what u r getting :wink:


#5

Hi @aksh1yadav, seems like I didn’t make it clear, but I got error when I tried to check it in an if :frowning:

Tried:
IF json_data(“memo”).ToString is Nothing
IF json_data(“memo”).ToString.IsNullOrEmpty
IF json_data(“memo”).ToString <> “”
But all of them tried the below error:
"message": “If : Object reference not set to an instance of an object.”,


#6

@whyyouandi , I haven’t worked much on JSON,

But we can implement dictionary concept of checking the Key exists or not i.e .ContainsKey method
Convert the JSON to dictionary while using Deserializing JSON by changing the type argument to Dictionary(of string,String)

On successful conversion you can use .ContainsKey method

Regards,
Dom :slight_smile:


#7

Hi @whyyouandi

Use below code in IF condition.

IsNothing(json_data(“memo”))

I checked and its working.

Thanks.
Udaykumar


#8

Hello @Dominic, thank you for your response.
It was new to me that we can convert a JSON text to a dictionary.
But I know less of programming, and setting Dictionary(Of String, String)
made me worry, how about if the data contains Date or other type? The conversion seems difficult.

But I tried to convert the JSON string to Dictionary, and I can check the Key using .ContainsKey well.
Will keep it in mind, thank you.


#9

Thank you @UdayKumar, it worked for my case.
It’s so bad we don’t have isNothingOrEmpty here. But we can work it around, thank you!