Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check if key/value is present in json

So, here’s what I am trying to do.

Given key and value, I am trying to see if both are present in json.

for eg: I got this json from response

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{"name":"John", "age":30, "car":null}

The code should return True only if both key and value are in json(response)

key: name
value: John

In this case the response should be TRUE

obj = json.loads(json_string) #response_json
key = body.get("key")  #gets_key
value = body.get("value") #gets_value

>Solution :

To test whether the key "name" has the value "John" in your obj dict, you’d do:

return obj.get("name") == "John"`

In the above example "name" is the key (it’s the argument to get) and "John" is being compared to the value that is returned by get.

Note that return only has meaning within a function body (i.e. this code should be part of some larger def statement that defines a function).

In your original code, body hasn’t been defined, so I’d expect body.get to raise an error. Calling obj.get("key") would return the value associated with a key called literally "key", and obj.get("value") would get the value associated with a key called "value". I don’t think either of these are what you want.

If you wanted to use variables called key and value that would look more like:

key = "name"
value = "John"
return obj.get(key) == value

Note that when we’re referring to a variable called key, we use the variable name without quotes; that’s what differentiates a variable from a string literal (key is a variable called key that can reference any string or other object we assign to it, "key" is the actual specific string "key").

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading