How To Solve “NameError: Name ‘json’ Is Not Defined” In Python?

NameError: name 'json' is not defined in Python

“NameError: name ‘json’ is not defined” in Python is a popular error related to the library JSON. You can read the explanations below to have more knowledge about this error of causes and solutions.

How does the “NameError: name ‘json’ is not defined” in Python happen?

This error happens due to only one reason. Essentially, it might be because you are calling a function from the JSON library but forgot to import them first. For example, calling json.dumps() to convert a Python object into a JSON string but not import json library first.

# Calling json.dumps()
print(json.dumps(2022))

Output

Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print(json.dumps(2))
NameError: name 'json' is not defined

How to solve this error?

As we have explained, you need the JSON library to implement the functions such as dumps() or loads() and many other functions (read this documentation). To import the JSON library, all you have to do is to declare import JSON at the head of the program:

import json
 
# Calling json.dumps()
print(json.dumps(2022))

Output:

2022

If you have a JSON, you should use the json.loads() to parse it and get the Python object. Another example, which will call the json.load() method:

import json
 
# Calling json.load()
print(json.loads("[2022]"))

Output:

[2022]

However, if you think that you have not installed this library in your Python interpreter and you want to avoid installing any external libraries, don’t worry, and this library is a built-in module, so you don’t have to install it with pip or carry out any installation. Just import it and use it.

Importing the JSON library not only makes your code run but also can help you reduce the library’s declaration when calling its method.

from json import loads,dumps
 
# Calling json.dumps()
print(dumps(2022))
 
# Calling json.load()
print(loads("[2022]"))

Output:

2022
[2022]

As you can see in the example below, you don’t have to call json.dump() or json.load() anymore. Because we have declared them in the import command. This could help you save time when coding because of shorter codes. 

Summary

We have learned how to deal with the NameError: name ‘json’ is not defined in Python. You can solve it quickly by checking if the library JSON was imported correctly before use and reading our other tutorials.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *