Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if key is missing after loading json from file in python

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.

like image 941
Philipp Klos Avatar asked May 23 '17 22:05

Philipp Klos


People also ask

How do you check if a key exists in a JSON file in Python?

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.

How do you check if a JSON object contains a key 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.

Can JSON have value without key?

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.


2 Answers

"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
like image 179
Martin Peck Avatar answered Sep 19 '22 00:09

Martin Peck


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.

like image 37
elethan Avatar answered Sep 22 '22 00:09

elethan