You can use a dictionary comprehension:

data = json.loads('{"foo":"5", "bar":""}')
res = {k: v if v != '' else None for k, v in data.items()}

{'foo': '5', 'bar': None}

This will only deal with the first level of a nested dictionary. You can use a recursive function to deal with the more generalised nested dictionary case:

def updater(d, inval, outval):
    for k, v in d.items():
        if isinstance(v, dict):
            updater(d[k], inval, outval)
        else:
            if v == '':
                d[k] = None
    return d

data = json.loads('{"foo":"5", "bar":"", "nested": {"test": "", "test2": "5"}}')

res = updater(data, '', None)

{'foo': '5', 'bar': None,
 'nested': {'test': None, 'test2': '5'}}
Answer from jpp on Stack Overflow
๐ŸŒ
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 - import json json_data = '{"name": "John", "age": 25, "city": "", "email": null}' parsed_json = json.loads(json_data) empty_values = [not value for value in parsed_json.values()] result = any(empty_values) print(f"Does the JSON object have empty values? {result}") ... In this example, below code employs the json and jsonpath_ng modules to process a JSON string (json_data). It loads the data into a Python dictionary (parsed_json) and utilizes a JSONPath expression to find elements with null or empty values.
Discussions

python - parse empty string using json - Stack Overflow
I was wondering if there was a way to use json.loads in order to automatically convert an empty string in something else, such as None. More on stackoverflow.com
๐ŸŒ stackoverflow.com
August 26, 2018
python 3.x - Load an empty string as a JSON in Python3 - Stack Overflow
I can not use an empty string in json.loads(). Python 3.6.4 (default, Jan 5 2018, 02:13:53) [GCC 7.2.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> More on stackoverflow.com
๐ŸŒ stackoverflow.com
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
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
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ check-if-python-json-object-is-empty
Check If Python Json Object is Empty - GeeksforGeeks
July 23, 2025 - In this example, below code checks if two JSON objects, `Geeks` (empty) and `GeeksTutorial` (with data), are empty and prints the corresponding messages. In this instance, it prints "JSON object 1 is empty." for `Geeks` and "JSON object 2 is not empty." along with the contents of `GeeksTutorial`. ... # JSON object 1 Geeks = {} # JSON object 2 GeeksTutorial = { "title": "Introduction to Python", "author": "GeeksforGeeks", "topics": ["Basics", "Data Structures", "Functions", "Modules"], } # Check if the JSO
๐ŸŒ
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.
Find elsewhere
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ json.html
JSON encoder and decoder โ€” Python 3.14.7 documentation
indent (int | str | None) โ€“ If a positive integer or string, JSON array elements and object members will be pretty-printed with that indent level. A positive integer indents that many spaces per level; a string (such as "\t") is used to indent each level. If zero, negative, or "" (the empty string), only newlines are inserted.
Top answer
1 of 1
2

You can do this by defining an object_hook to pass to json.loads.

From the docs:

object_hook is an optional function that will be called with the result of any object literal decoded (a dict). The return value of object_hook will be used instead of the dict.

Given this dict:

>>> pprint(d)
{'campaign_id': '9c1c6cd7-fd4d-480b-8c80-07091cdd4103',
 'creation_date': 1530804132,
 'float': 1.2345,
 'objects': [{'full_name': '', 'id': 12345}],
 'strs': ['', 'abc', {'a': ''}],
 'top_str': ''}

This pair of functions will recurse over the result of json.loads and change instance of the empty string to 'N/A'.

def transform_dict(mapping=None):
    if mapping is None:
        mapping = {}
    for k, v in mapping.items():
        if v == '':
            mapping[k] = 'N/A'
        elif isinstance(v, dict):
            mapping[k] = transform_dict(v)
        elif isinstance(v, list):
            mapping[k] = transform_list(v)
        else:
            # Make it obvious that we aren't changing other values
            pass
    return mapping


def transform_list(lst):
    for i, x in enumerate(lst):
        if x == '':
            lst[i] = 'N/A'
        elif isinstance(x, dict):
            lst[i] = transform_dict(x)
        elif isinstance(x, list):
            lst[i] = transform_list(x)
        else:
            # Make it obvious that we aren't changing other values
            pass
    return lst

>>> res = json.loads(
        json.dumps(d), 
        parse_float=decimal.Decimal, 
        object_hook=transform_dict,
    )
>>> pprint(res)
{'campaign_id': '9c1c6cd7-fd4d-480b-8c80-07091cdd4103',
 'creation_date': 1530804132,
 'float': Decimal('1.2345'),
 'objects': [{'full_name': 'N/A', 'id': 12345}],
 'strs': ['N/A', 'abc', {'a': 'N/A'}],
 'top_str': 'N/A'}

Note that this approach depends on the input json being a json object ({...}).

๐ŸŒ
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...
๐ŸŒ
Hiredgun
hiredgun.tech โ€บ home โ€บ apis โ€บ handling empty json strings
Handling Empty JSON Strings - hiredgun.tech
December 8, 2024 - The JSON is reduced to just the content I require by use of the Compose action โ€“ see my recent post Simplify JSON Content Before Parsing for details on how to do this. The simplified JSON is subsequently parsed by the Parse JSON action, and the output is entered into Dataverse. Below are 2 returned objects. The first has a complete set of data but the second returns an empty string for Registration Year and Company Status.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 65556852 โ€บ appending-into-an-empty-json-file-in-python
arrays - Appending into an empty JSON file in python - Stack Overflow
You want a single JSON string in the output file? Process everything into a list and then json.dump that one list. ... @tdelaney I have edited the question to show the example of the new JSON file. I just want to append as the data gets parsed to save time ... You are reading and writing a single JSON list object so there isn't a lot of opportunity to do things iteratively. Your current code fails because you can't write a python dictionary (f.write(entry)) without some sort of serialization.
๐ŸŒ
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.
๐ŸŒ
GitHub
github.com โ€บ samuelcolvin โ€บ pydantic โ€บ issues โ€บ 4253
An empty string is a valid JSON attribute name ยท Issue #4253 ยท pydantic/pydantic
July 19, 2022 - pydantic version: 1.9.0 pydantic compiled: False install path: /Users/s_tsaplin/projects/github.com/sergeytsaplin/pydantic/pydantic python version: 3.9.13 (main, May 19 2022, 14:10:54) [Clang 13.1.6 (clang-1316.0.21.2)] platform: macOS-12.4-x86_64-i386-64bit optional deps. installed: ['devtools', 'dotenv', 'email-validator', 'typing-extensions'] from pydantic import BaseModel, Field class Model(BaseModel): empty_string_key: int = Field(alias='') data = {'': 123} m = Model(**data) m.dict(by_alias=True)
Author: pydantic
๐ŸŒ
FreeKB
freekb.net โ€บ Article
Determine if JSON key contains an empty list
#!/usr/bin/python3 import json raw_json = '{ "foo": [ "Hello", "World" ] }' 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 does NOT contain an empty list