Pythonにおける「NameError: name 'json' is not defined」の解決方法

PythonPythonBeginner
今すぐ練習

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

Introduction

Python is a powerful programming language, but even experienced developers encounter errors during development. One common error that beginners face is the NameError: name 'json' is not defined when trying to work with JSON data. This tutorial will guide you through understanding, reproducing, and resolving this error to ensure your Python code runs smoothly.

By the end of this lab, you will understand why this error occurs and learn the correct way to import and use the JSON module in your Python applications.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/FileHandlingGroup(["File Handling"]) python(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/ModulesandPackagesGroup(["Modules and Packages"]) python(("Python")) -.-> python/ErrorandExceptionHandlingGroup(["Error and Exception Handling"]) python/FunctionsGroup -.-> python/scope("Scope") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") python/ModulesandPackagesGroup -.-> python/importing_modules("Importing Modules") python/ErrorandExceptionHandlingGroup -.-> python/raising_exceptions("Raising Exceptions") python/FileHandlingGroup -.-> python/file_reading_writing("Reading and Writing Files") python/PythonStandardLibraryGroup -.-> python/data_serialization("Data Serialization") subgraph Lab Skills python/scope -.-> lab-417445{{"Pythonにおける「NameError: name 'json' is not defined」の解決方法"}} python/build_in_functions -.-> lab-417445{{"Pythonにおける「NameError: name 'json' is not defined」の解決方法"}} python/importing_modules -.-> lab-417445{{"Pythonにおける「NameError: name 'json' is not defined」の解決方法"}} python/raising_exceptions -.-> lab-417445{{"Pythonにおける「NameError: name 'json' is not defined」の解決方法"}} python/file_reading_writing -.-> lab-417445{{"Pythonにおける「NameError: name 'json' is not defined」の解決方法"}} python/data_serialization -.-> lab-417445{{"Pythonにおける「NameError: name 'json' is not defined」の解決方法"}} end

Understanding Python NameError

A NameError in Python occurs when the interpreter cannot find a variable, function, or module that you are trying to use. This error typically has one of the following causes:

  1. Using a variable before defining it
  2. Misspelling a variable or function name
  3. Forgetting to import a module before using it

Exploring a Simple NameError Example

Let's start by creating a simple script that generates a NameError. Open the code editor and create a new file named name_error_example.py in the /home/labex/project directory with the following content:

## This script demonstrates a simple NameError
print("Starting the script...")

## Try to use a variable that hasn't been defined
print(undefined_variable)

print("This line won't execute because of the error above")

Now, let's run this script. Open a terminal and execute:

python3 /home/labex/project/name_error_example.py

You should see an output similar to:

Starting the script...
Traceback (most recent call last):
  File "/home/labex/project/name_error_example.py", line 5, in <module>
    print(undefined_variable)
NameError: name 'undefined_variable' is not defined

This error message tells us:

  • The error type: NameError
  • The specific issue: name 'undefined_variable' is not defined
  • The location: Line 5 in the script

The Python interpreter raised this error because we tried to use a variable called undefined_variable without defining it first. This is the same type of error that occurs when trying to use the json module without importing it.

Reproducing the JSON NameError

Now that we understand what a NameError is, let's reproduce the specific error mentioned in the title: NameError: name 'json' is not defined.

Creating a Script with JSON Error

Create a new file named json_error.py in the /home/labex/project directory with the following content:

## This script tries to use the json module without importing it

## Sample JSON string
json_string = '{"name": "Alice", "age": 30, "city": "New York"}'

## Try to parse JSON without importing the json module
parsed_data = json.loads(json_string)

print("User data:", parsed_data)

In this script, we're trying to use the json.loads() function to parse a JSON string, but we haven't imported the json module first.

Let's run the script and see what happens:

python3 /home/labex/project/json_error.py

You should see an error message like this:

Traceback (most recent call last):
  File "/home/labex/project/json_error.py", line 7, in <module>
    parsed_data = json.loads(json_string)
NameError: name 'json' is not defined

This is the exact error we're trying to solve in this lab! The Python interpreter cannot find the json module because we didn't import it before trying to use it.

Understanding the JSON Module

Before we fix the error, let's understand what the JSON module is:

  • JSON (JavaScript Object Notation) is a lightweight data interchange format
  • Python includes a built-in json module to work with JSON data
  • The json module provides methods to encode Python objects as JSON strings and decode JSON strings into Python objects
  • Common functions include json.dumps() (convert Python to JSON) and json.loads() (convert JSON to Python)

Like all Python modules, you need to import the json module before you can use its functions.

Fixing the JSON NameError

Now that we've reproduced the error, let's fix it by properly importing the JSON module.

Adding the Import Statement

Open the json_error.py file and update it by adding an import statement at the top:

## This script properly uses the json module by importing it first
import json

## Sample JSON string
json_string = '{"name": "Alice", "age": 30, "city": "New York"}'

## Parse JSON after importing the json module
parsed_data = json.loads(json_string)

print("User data:", parsed_data)

The key change is adding import json at the beginning of the file. This tells Python to load the JSON module before we try to use it.

Running the Fixed Script

Save the file and run it again:

python3 /home/labex/project/json_error.py

This time, you should see the script execute successfully with output:

User data: {'name': 'Alice', 'age': 30, 'city': 'New York'}

The script now runs without errors because we've properly imported the json module before using it.

Alternative Import Methods

There are several ways to import modules in Python:

  1. Import the entire module (as we did above):

    import json
    ## Use as json.function_name()
  2. Import specific functions from a module:

    from json import loads
    ## Use directly as loads()
  3. Import with an alias:

    import json as j
    ## Use as j.function_name()

Let's try the second method. Create a new file named json_import_variation.py with:

## Importing specific functions from the json module
from json import loads

## Sample JSON string
json_string = '{"name": "Bob", "age": 25, "city": "San Francisco"}'

## Parse JSON using the directly imported function
parsed_data = loads(json_string)

print("User data:", parsed_data)

Run this script to see that it also works:

python3 /home/labex/project/json_import_variation.py

You should see:

User data: {'name': 'Bob', 'age': 25, 'city': 'San Francisco'}

This demonstrates that there are multiple valid ways to import the JSON module, all of which will prevent the NameError.

Working with JSON Data

Now that we know how to properly import the JSON module, let's explore how to use it for common JSON operations.

Creating a Complete JSON Example

Create a new file named json_operations.py with the following content:

## Complete example of working with JSON in Python
import json

## 1. Converting Python object to JSON string (serialization)
user = {
    "name": "Charlie",
    "age": 28,
    "is_student": False,
    "courses": ["Python", "Data Science", "Web Development"],
    "address": {
        "street": "123 Tech Lane",
        "city": "Boston",
        "zipcode": "02101"
    }
}

## Convert Python dictionary to JSON string
json_string = json.dumps(user, indent=2)
print("JSON string created from Python object:")
print(json_string)
print("\n" + "-"*50 + "\n")

## 2. Parse JSON string to Python object (deserialization)
parsed_user = json.loads(json_string)
print("Python object created from JSON string:")
print("Name:", parsed_user["name"])
print("Age:", parsed_user["age"])
print("Courses:", parsed_user["courses"])
print("City:", parsed_user["address"]["city"])
print("\n" + "-"*50 + "\n")

## 3. Writing JSON to a file
with open("/home/labex/project/user_data.json", "w") as json_file:
    json.dump(user, json_file, indent=2)
print("JSON data written to user_data.json")

## 4. Reading JSON from a file
with open("/home/labex/project/user_data.json", "r") as json_file:
    loaded_user = json.load(json_file)
print("JSON data loaded from file. User name:", loaded_user["name"])

This script demonstrates four common JSON operations:

  1. Converting a Python object to a JSON string using json.dumps()
  2. Parsing a JSON string into a Python object using json.loads()
  3. Writing JSON data to a file using json.dump()
  4. Reading JSON data from a file using json.load()

Run the script:

python3 /home/labex/project/json_operations.py

You should see output similar to:

JSON string created from Python object:
{
  "name": "Charlie",
  "age": 28,
  "is_student": false,
  "courses": [
    "Python",
    "Data Science",
    "Web Development"
  ],
  "address": {
    "street": "123 Tech Lane",
    "city": "Boston",
    "zipcode": "02101"
  }
}

--------------------------------------------------

Python object created from JSON string:
Name: Charlie
Age: 28
Courses: ['Python', 'Data Science', 'Web Development']
City: Boston

--------------------------------------------------

JSON data written to user_data.json
JSON data loaded from file. User name: Charlie

The script also created a file named user_data.json. Let's look at its contents:

cat /home/labex/project/user_data.json

You should see the JSON data formatted with proper indentation:

{
  "name": "Charlie",
  "age": 28,
  "is_student": false,
  "courses": ["Python", "Data Science", "Web Development"],
  "address": {
    "street": "123 Tech Lane",
    "city": "Boston",
    "zipcode": "02101"
  }
}

You have now successfully learned how to work with JSON data in Python, including how to avoid the NameError: name 'json' is not defined error by properly importing the module.

Summary

In this lab, you have learned:

  • What a NameError is in Python and common causes for this exception
  • How to identify and troubleshoot the specific error NameError: name 'json' is not defined
  • The proper way to import the JSON module using different import syntax options
  • How to work with JSON data in Python, including:
    • Converting Python objects to JSON strings
    • Parsing JSON strings into Python objects
    • Writing JSON data to files
    • Reading JSON data from files

These skills are fundamental for working with data in Python, especially when building applications that communicate with web services or store configuration data. By understanding how to properly import and use modules, you can avoid common errors and write more robust Python code.

Remember that this pattern applies to all Python modules, not just the JSON module. Always ensure you have the proper import statements at the beginning of your files before using any external functionality.