I'm getting the JSON via:
with open("config.json") as data_file:
global data
data = json.load(data_file)
And I want to check if the data["example"]
is empty or not.
Check if the key exists or not in JSON if it is present directly to access its value instead of iterating the entire JSON. Note: We used json. loads() method to convert JSON encoded data into a Python dictionary. After turning JSON data into a dictionary, we can check if a key exists or not.
JsonObject::containsKey() returns a bool that tells whether the key was found or not: true if the key is present in the object. false if the key is absent of the object.
No, in JSON notation, an object is an unordered set of key/value pairs, and both the key and the value are required elements. That's perfectly valid JSON.
"example" in data.keys()
will return True or False, so this would be one way to check.
So, given JSON like this...
{ "example": { "title": "example title"}}
And given code to load the file like this...
import json
with open('example.json') as f:
data = json.load(f)
The following code would return True or False:
x = "example" in data # x set to True
y = "cheese" in data # y set to False
You can try:
if data.get("example") == "":
...
This will not raise an error, even if the key "example"
doesn't exist.
What is happening in your case is that data["example"]
does not equal ""
, and in fact there is no key "example"
so you are probably seeing a KeyError
which is what happens when you try to access a value in a dict using a key that does not exist. When you use .get("somekey")
, if the key "somekey"
does not exist, get()
will return None
and will return the value otherwise. This is important to note because if you do a check like:
if not data.get("example"):
...
this will pass the if test if data["example"]
is ""
or if the key "example"
does not exist.
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