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.
๐ŸŒ
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 - import json json_data = ... (empty_values) to check for empty values in the dictionary. The result is determined using the any() function....
Discussions

python - checking if json value is empty - Stack Overflow
Occasionally there is no name provided so the JSON-Value will be set to "". How can I check if the value is given? 2017-07-17T01:17:00.403Z+00:00 ... I get "Error: 'dict' object has no attribute 'find'" when trying to use your code 2017-07-17T01:18:31.047Z+00:00 ... @siryx sounds like you're using an older version of python ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
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 to check if JSON is empty. If not, append new data - Stack Overflow
I am trying to check to see if a JSON is empty within a for loop, and if it is not to append new data. What I am attempting to achieve is the first time around the JSON will be empty, so it needs to More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - How to check if JSON file contains only empty array - Stack Overflow
But my JSON files can be really huge and I do not want to load them all. Can I check if file contains nothing but empty array in other way? Check if my file's weight is 2 bytes (isn't it lame?)? More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
CopyProgramming
copyprogramming.com โ€บ howto โ€บ check-if-json-is-empty-python-code-example
Check If JSON Is Empty in Python: Complete Guide with 2026 Best Practices
December 21, 2025 - An empty JSON objectโ€”represented as {} in JSON syntaxโ€”converts to an empty Python dictionary when parsed. The simplest and most Pythonic way to check if a JSON object is empty is using the not operator: if not json_obj: returns True for empty dictionaries, while len(json_obj) == 0 and json_obj ...
๐ŸŒ
FreeKB
freekb.net โ€บ Article
Determine if JSON key contains an empty list
#!/usr/bin/python3 import json raw_json = '{ "foo": [] }' try: parsed_json = json.loads ( raw_json ) except Exception as exception: print(f"Got the following exception: {exception}") if len(parsed_json['foo']) == 0: print("The foo key contains an empty list") else: print("The foo key does NOT contain an empty list") Running this Python script should return the following. ~]$ python example.py The foo key contains an empty list ยท On the other hand, if the list is not empty.
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:
๐ŸŒ
Codeigo
codeigo.com โ€บ home โ€บ check if json object has empty value in python
Check if Json Object Has Empty Value in Python - Codeigo
April 19, 2023 - Suppose we want to look for products with empty values in some keys. Remember that you need to convert JSON data into a Python dictionary before using it as a regular dictionary. This is because JSON data format is of string (<str>) datatype in Python. For this reason, we will work with a Python dictionary to check for empty values.
Find elsewhere
๐ŸŒ
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
Instead, just check to see if the requested data is empty and append to the original list. BTW, empty lists and dicts are "falsey" so you don't need to check their lengths. if r_json:=r.json(): # python 3.8+ print('Appending to JSON file') json_data.append(r_json) else: print('Empty JSON file')
๐ŸŒ
YouTube
youtube.com โ€บ codemore
python check json is empty - YouTube
Download this code from https://codegive.com Certainly! Checking if a JSON object is empty in Python involves verifying if it contains any data or if it's co...
Published: December 23, 2023
Views: 119
๐ŸŒ
Restack
restack.io โ€บ p โ€บ python-json-empty-object-answer-cat-ai
Where product teams design, test and optimize agents at Enterprise Scale โ€” Restack
May 3, 2025 - The open-source stack enabling product teams to improve their agent experience while engineers make them reliable at scale on Kubernetes.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 36861749 โ€บ checking-whether-a-json-dictionary-is-empty-or-not-and-storing-in-a-list
python - Checking whether a JSON dictionary is empty or not and storing in a list - Stack Overflow
July 29, 2016 - If the json response is empty like below, how to store "ACC deleted" in the list? ... You can check if data is empty in your script and if so add a new entry 'ACC deleted' to the list.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 63341961 โ€บ check-if-json-file-is-empty-and-than-delete-it-from-a-directory-in-python
Check if .json file is empty and than delete it from a directory in python - Stack Overflow
August 10, 2020 - basically i scrapped data to json file from a website iterating date. but on holidays the data is empty. like 2020-07-04.json has [ ] brackets only. so i want to check those files and delete it. ... import requests import datetime import json start_date = datetime.date(2020, 7, 1) end_date = datetime.date(2020, 8, 9) url = f'https://newweb.nepalstock.com.np/api/nots/nepse-data/today-price? sort=symbol&size=5&businessDate={start_date}' response = requests.get(url) data = response.json() if data: with open(str(start_date) +'.json', 'w') as json_file: json.dump(data, json_file) start_date += delta
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)