Fix - NameError: name 'json' is not defined in Python

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

banner

Photo by Raychan

Fix - NameError: name 'json' is not defined in Python #

The Python "NameError: name 'json' is not defined" occurs when we use the json module without importing it first. To solve the error, import the json module before using it - import json.

nameerror name json is not defined

Here is an example of how the error occurs.

main.py
# ⛔️ NameError: name 'json' is not defined json_str = json.dumps({'name': 'Alice', 'age': 30})

To solve the error, we have to import the json module.

main.py
# ✅ import json first import json json_str = json.dumps({'name': 'Alice', 'age': 29}) print(json_str) # 👉️ '{"name": "Alice", "age": 29}' print(type(json_str)) # 👉️ <class 'str'> native_python_obj = json.loads(json_str) print(native_python_obj) # 👉️ {'name': 'Alice', 'age': 29} print(type(native_python_obj)) # 👉️ <class 'dict'>

Even though the json module is in the Python standard library, we still have to import it before using it.

Make sure you haven't used a capital letter j when importing json because module names are case-sensitive.

Also, make sure you haven't imported json in a nested scope, e.g. a function. Import the module at the top level to be able to use it throughout your code.

An alternative to importing the entire json module is to import only the functions and constants that your code uses.

main.py
from json import dumps, loads json_str = dumps({'name': 'Alice', 'age': 29}) print(json_str) # 👉️ '{"name": "Alice", "age": 29}' print(type(json_str)) # 👉️ <class 'str'> native_python_obj = loads(json_str) print(native_python_obj) # 👉️ {'name': 'Alice', 'age': 29} print(type(native_python_obj)) # 👉️ <class 'dict'>

The example shows how to import only the dumps and loads functions from the json module.

Instead of accessing the members on the module, e.g. json.loads, we now access them directly.

You should pick whichever approach makes your code easier to read.

For example, when we use an import such as import json, it is much harder to see which functions from the json module are being used in the file.

Conversely, when we import specific functions, it is much easier to see which functions from the json module are being used.

However, you will most likely be using only 2 functions from the json module - json.dumps() and json.loads().

The json.dumps function is used to serialize a Python object to a JSON formatted string.

Conversely, you can use the json.loads function to deserialize a JSON string to a native Python object.

You can view all of the functions the json module provides by visiting the official docs.

Use the search field on my Home Page to filter through my more than 1,000 articles.