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 Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › check-if-python-json-object-is-empty
Check If Python Json Object is Empty - GeeksforGeeks
July 23, 2025 - In this article, we explored three different methods to check if a JSON object is empty in Python.
Discussions

How to parse completely empty JSON key/values?
I'm not sure why you would want that, or what the logic is here. Why does an empty dict map to an empty string? How are you selecting the values to fetch for the other dicts? Are all the dicts guaranteed to either be empty or have a single key only? More on reddit.com
🌐 r/learnpython
7
3
November 18, 2022
python - How can I create the empty json object? - Stack Overflow
If mydata is empty, then this will fail and the default argument in the get won't save you. 2015-08-28T14:51:40.193Z+00:00 ... Save this answer. ... Show activity on this post. loads() takes a json formatted string and turns it into a Python object like dict or list. More on stackoverflow.com
🌐 stackoverflow.com
Python: Json file become empty - Stack Overflow
Here is my code of accessing&editing the file: def edit_default_settings(self, setting_type, value): with open("cam_settings.json", "r") as f: cam_se... More on stackoverflow.com
🌐 stackoverflow.com
python - checking if json value is empty - Stack Overflow
@viraptor I've updated the answer ... of empty strings being falsey in python. 2017-07-17T01:17:44.143Z+00:00 ... 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['gme... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Quora
quora.com › How-do-you-declare-an-empty-JSON-in-Python
How to declare an empty JSON in Python - Quora
Answer (1 of 4): JSON is a serialization format that can represent certain kinds of objects as strings. An empty string is not a valid JSON representation of anything. If you try to decode an empty string using Python's standard [code ]json[/code] module, you'll get an error: [code]>>> import j...
🌐
GeeksforGeeks
geeksforgeeks.org › python › check-if-json-object-has-empty-value-in-python
Check if Json Object has Empty Value in Python - GeeksforGeeks
July 23, 2025 - This Python code uses the json module to parse a JSON string (json_data) into a Python dictionary (parsed_json). It then creates a list (empty_values) to check for empty values in the dictionary. The result is determined using the any() function.
🌐
FreeKB
freekb.net › Article
Determine if JSON key contains an empty list
#!/usr/bin/python3 import json ... the following exception: {exception}") print(parsed_json) An if statement can be used to determine if the list is empty....
Find elsewhere
🌐
Python Forum
python-forum.io › thread-27694.html
empty json file error
I wrote this and since it creates an empty file it give me an error. with open('food.json', 'r+') as file: food = json.load(file)Error:Traceback (most recent call last): File 'c:/Users/User/MyStuff/mltipls.py', line 4, in foo...
Top answer
1 of 3
2

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'):
2 of 3
0

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:
🌐
GitHub
gist.github.com › nlohmann › c899442d8126917946580e7f84bf7ee7
Remove empty arrays, objects or null elements from a JSON value · GitHub
thank you !!! I needed a function to remove all keys with (values == "") from a very large, very nested JSON, and changing a little bit the function empty() worked flawlessly. def empty(x): return x is None or x == {} or x == [] or x == "" Copy link · Copy Markdown ·
🌐
Stack Overflow
stackoverflow.com › questions › 73558736 › how-to-check-if-json-is-empty-if-not-append-new-data
python - How to check if JSON is empty. If not, append new data - Stack Overflow
You create a list json_data = [] to hold decoded data, but then replace it with the first decoded data. If that data is also empty, then json_data is still empty, and it keeps going until you finally get something that isn't empty.
🌐
Stack Overflow
stackoverflow.com › questions › 79741358 › json-file-keeps-showing-up-as-empty
python - JSON File Keeps Showing Up as Empty? - Stack Overflow
This works fine for me. Are you sure you get an empty {} and say not a UnicodeDecodeError exception that might require you on say Windows to include the parameter encoding="utf-8"? Are you sure any outstanding edits to you json have been saved?
Top answer
1 of 1
3

There are quite a few issues with your code, ie

program crashing if the file does not exist:

with open(storage_path,'r') as f:

opening storage_path for writing but actually not writing anything:

    print('each time I am creating the new one')
    with open(storage_path,'w') as f:
        data_base = {}
    f.close()

And actually if you happened to have f.seek(2) == 2, the json.load(f) would also crash since at this point you moved the file pointer at the 3rd char so subsequent read in json.load() wouldn't get the whole content.

Here's a fixed version that should work AFAICT:

import argparse
import os
import tempfile
import json

storage = argparse.ArgumentParser()
storage.add_argument("--key", help="input key's name")
storage.add_argument("--val", help="value of key", default=None)
args = storage.parse_args()
storage_path = os.path.join(tempfile.gettempdir(), 'storage.data')

data_base = None
if os.path.exists(storage_path):
    with open(storage_path,'r') as f:
        try:
            data_base = json.load(f)
            print('loaded that: ',data_base)
        except Exception as e:
            print("got %s on json.load()" % e)

if data_base is None:
    print('each time I am creating the new one')
    data_base = {}
    with open(storage_path,'w') as f:
        json.dump(data_base, f)

# don't prevent the user to set `"Not found" as value, if might
# be a legitimate value.
# NB : you don't check if `args.key` is actually set... maybe you should ?

sentinel = object()    
if data_base.get(args.key, sentinel) is sentinel:         
    if args.val is not None:
        data_base[args.key] = args.val
        with open(storage_path, 'w') as f:
            json.dump(data_base, f)
            print('dumped this: ',data_base)