Last modified: Mar 05, 2025 By Alexander Williams
Fix Python NameError: Name 'json' Not Defined
Encountering a NameError in Python can be frustrating. One common error is NameError: Name 'json' Not Defined. This article explains why this error occurs and how to fix it.
What Causes the NameError: Name 'json' Not Defined?
The error occurs when you try to use the json
module without importing it first. Python does not recognize json
as a built-in function or module.
For example, running the following code will raise the error:
data = json.loads('{"name": "John"}')
The output will be:
NameError: name 'json' is not defined
How to Fix the NameError: Name 'json' Not Defined
To fix this error, you need to import the json
module at the beginning of your script. Here’s how you can do it:
import json
data = json.loads('{"name": "John"}')
print(data)
The output will be:
{'name': 'John'}
By importing the json
module, Python recognizes it, and the error is resolved.
Common Scenarios Where This Error Occurs
This error often occurs in scenarios where developers forget to import the json
module. It can also happen when working with APIs or reading JSON files.
For example, when parsing JSON data from an API response:
import requests
response = requests.get('https://api.example.com/data')
data = json.loads(response.text) # This will raise the NameError
To fix this, ensure you import the json
module:
import requests
import json
response = requests.get('https://api.example.com/data')
data = json.loads(response.text)
print(data)
Related Errors and Solutions
If you encounter similar errors like NameError: Name 'cursor' Not Defined or NameError: Name 'session' Not Defined, the solution is often the same. Ensure you import the necessary modules or define the variables before using them.
For more details, check out our guides on Fix Python NameError: Name 'cursor' Not Defined and Fix Python NameError: Name 'session' Not Defined.
Conclusion
The NameError: Name 'json' Not Defined is a common issue in Python. It happens when the json
module is not imported. By importing the module at the beginning of your script, you can easily resolve this error.
Always remember to check your imports and ensure all required modules are included. For more tips on handling Python errors, explore our other guides like Fix Python NameError in Multi-threading and Async.