Check both, the key existence and its length:
import json, sys
obj=json.load(sys.stdin)
if not 'results' in obj or len(obj['results']) == 0:
exit(0)
else:
exit(1)
Answer from Thiago Rossener on Stack OverflowCheck both, the key existence and its length:
import json, sys
obj=json.load(sys.stdin)
if not 'results' in obj or len(obj['results']) == 0:
exit(0)
else:
exit(1)
import json, sys
obj=json.load(sys.stdin)
if len(obj["results"])==0:
exit(0)
else:
exit(1)
try using the length of obj["results"]
How to parse completely empty JSON key/values?
python - How can I create the empty json object? - Stack Overflow
Python: Json file become empty - Stack Overflow
python - checking if json value is empty - Stack Overflow
Let's say I have a JSON object like this:
{"Data":[{"key1":"value1"},{"key2":"value2"},
{}]
}
If I wanted a list to look as follows: ['value1', 'value2', '']. How would I go about pulling in that null JSON key/value? Is that possible?
Thank you!
Simply:
json.loads(request.POST.get('mydata', '{}'))
Or:
data = json.loads(request.POST['mydata']) if 'mydata' in request.POST else {}
Or:
if 'mydata' in request.POST:
data = json.loads(request.POST['mydata'])
else:
data = {} # or data = None
loads() takes a json formatted string and turns it into a Python object like dict or list. In your code, you're passing dict() as default value if mydata doesn't exist in request.POST, while it should be a string, like "{}". So you can write -
json_data = json.loads(request.POST.get('mydata', "{}"))
Also remember, the value of request.POST['mydata'] must be JSON formatted, or else you'll get the same error.
I can't see any issues with the code itself, but there can be an issue with the execution environment. Are you running the code in a multi-threaded environment or running multiple instances of the same program at once?
This situation can arise if this code is executed parallelly and multiple threads/processes try to access the file at the same time. Try logging each time the function was executed and if the function was executed successfully. Try exception handlers and error logging.
If this is a problem, using buffers or singleton pattern can solve the issue.
As @Chels said, the file is truncated when it's opened with 'w'. That doesn't explain why it stays that way; I can only imagine that happening if your code crashed. Maybe you need to check logs for code crashes (or change how your code is run so that crash reasons get logged, if they aren't).
But there's a way to make this process safer in case of crashes. Write to a separate file and then replace the old file with the new file, only after the new file is fully written. You can use os.replace() for this. You could do this simply with a differently-named file:
with open(".cam_settings.json.tmp", 'w') as f:
json.dump(cam_settings, f, indent=4)
os.replace(".cam_settings.json.tmp", "cam_settings.json")
Or you could use a temporary file from the tempfile module.
You're misunderstanding how in works. in checks to see if a key exists in a dictionary, it does not index into a dictionary. That's what the square brackets do.
if 'title_jpn' in json_data['gmetadata'][0] is not "":
The above line will not evaluate as you expect. It should be.
if json_data['gmetadata'][0]['title_jpn'] is not "":
This can be further simplified because empty strings '' always evaluate to False in python. So instead of checking if the string is not empty, just check if it has any value at all like the following:
if json_data['gmetadata'][0]['title_jpn']:
If you're trying to guard against the fact that title_jpn might be optional and not always exist, you need to do two conditions in your if statement (which I think is what you were originally trying to do):
if 'title_jpn' in json_data['gmetadata'][0] and json_data['gmetadata'][0]['title_jpn']:
The above line first checks if the title_jpn key is present before trying to check if it's value is empty. This can be further simplified using the dictionary .get() method which allows you to supply a default.
if json_data['gmetadata'][0].get('title_jpn', None):
The above will check if title_jpn is in the dictionary and return the value if it does, or None as a default if it does not. Since None is interpreted as False in python, the if block will not run, which is the desired behaviour.
dict.get(key, default=None)
However, since .get() automatically sets the default value to None, you can simply do the following.
if json_data['gmetadata'][0].get('title_jpn'):
Your .get won't work, since this applies to dictionaries. As far as I know, "In" won't work either since this is the syntax for a For loop. Probably you want the "Find" method, since this matches a substring within a longer string (which is your goal, if I understand correctly). It'll return minus one if the string isn't found. So in your case, example use:
if json_data['gmetadata'][0].find('title_jpn') != -1:
Modify your reader script to this:
with open('favoriteColor.json') as inFile:
try:
colors = json.load(inFile)
except ValueError:
colors = []
This attempts to load the file as a json. If it fails due to a value error, we know that this is because the json is empty. Therefore we can just assign colors to an empty list. It is also preferable to use the "with" construct to load files since it closes them automatically.
I wouldn't take the approach you're trying. I would instead json.dump a dictionary, eg:
d = {'var1': '123', 'var2': [1, 2, 3]}
json.dump(d, fileout)
Then use dict.get to default it to a suitable value:
json_dict = json.load(filein)
favColor = json_dict.get('favColor', [])
Then you still have compulsory values that can except if not present using [] notation.
Puts the logic of missing values in your code instead of the json parsers...
"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.
Use coalescing to pass it something valid.
json.loads('' or 'null')
To give another way that worked for me, I used the inline if which returns an empty string if there is no data to load: As seen below I wanted to load the request form data which is the session id
session_id = json.loads(request.form['session_id']) if request.form['session_id'] else ''