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
{"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
CodePudding user response:
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"
).