杰瑞科技汇

Python json.load()如何正确使用?

Of course! It looks like you're asking about json.load() in Python. This is a fundamental function for working with JSON data.

Python json.load()如何正确使用?-图1
(图片来源网络,侵删)

I'll cover everything you need to know, from the basic syntax to common use cases and troubleshooting.

What is json.load()?

The json.load() function in Python's built-in json module is used to parse (read) a JSON data stream from a file-like object and convert it into a Python object (like a dictionary or a list).

Think of it as "loading" JSON data from a file into your Python script.


The Key Difference: load() vs loads()

This is a very common point of confusion. Here’s the simple breakdown:

Python json.load()如何正确使用?-图2
(图片来源网络,侵删)
Function What it Does Source Example
json.load() Parses data from a file (or a file-like object). A file object (e.g., open('file.json')) json.load(my_file_object)
json.loads() Parses data from a string. A Python string variable json.loads(my_json_string)
  • load -> File
  • loads -> String (the 's' stands for string)

How to Use json.load(): A Step-by-Step Guide

Let's walk through the most common use case: reading a JSON file.

Step 1: Create a Sample JSON File

First, create a file named data.json with the following content:

{
  "name": "John Doe",
  "age": 30,
  "isStudent": false,
  "courses": [
    {
      "title": "History",
      "credits": 3
    },
    {
      "title": "Math",
      "credits": 4
    }
  ],
  "address": null
}

Step 2: Write the Python Script

Now, create a Python script (e.g., read_json.py) in the same directory.

import json
# The 'with' statement is the recommended way to handle files
# as it automatically closes the file for you.
try:
    with open('data.json', 'r') as file:
        # Use json.load() to parse the file object
        data = json.load(file)
    # Now 'data' is a Python dictionary
    print("Successfully loaded JSON data!")
    print("-" * 20)
    # You can access the data using standard Python syntax
    print(f"Name: {data['name']}")
    print(f"Age: {data['age']}")
    print(f"Is Student: {data['isStudent']}")
    print("\nCourses:")
    for course in data['courses']:
        print(f"  - {course['title']} ({course['credits']} credits)")
    print(f"\nAddress: {data['address']}")
except FileNotFoundError:
    print("Error: The file 'data.json' was not found.")
except json.JSONDecodeError:
    print("Error: The file contains invalid JSON.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

Step 3: Run the Script

Execute the Python script from your terminal:

Python json.load()如何正确使用?-图3
(图片来源网络,侵删)
python read_json.py

Expected Output:

Successfully loaded JSON data!
--------------------
Name: John Doe
Age: 30
Is Student: False
Courses:
  - History (3 credits)
  - Math (4 credits)
Address: None

Handling Different JSON Data Types

The json module automatically converts JSON types to their Python equivalents:

JSON Type Python Type
object dict
array list
string str
number (int) int
number (real) float
true True
false False
null None

Common Errors and How to Fix Them

FileNotFoundError

This happens if the file path you provided is incorrect.

# ERROR
with open('wrong_file_name.json', 'r') as f:
    data = json.load(f)

Fix: Double-check your file name and path. Make sure the file exists in the location you expect.

json.decoder.JSONDecodeError

This is the most common error when working with JSON. It means the file you are trying to read does not contain valid JSON.

Causes:

  • A missing comma: {"name": "John" "age": 30} (should be {"name": "John", "age": 30})
  • A trailing comma: {"name": "John", "age": 30,} (invalid in JSON)
  • Using single quotes instead of double quotes: {'name': 'John'} (should be {"name": "John"})
  • Mismatched brackets or braces.

Fix: Carefully review your JSON file for syntax errors. Using a JSON linter or an online JSON formatter can help you spot these issues easily.

TypeError: the JSON object must be str, bytes or bytearray, not 'TextIOWrapper'

This error happens when you accidentally use json.loads() on a file object instead of json.load().

# ERROR
with open('data.json', 'r') as file:
    # json.loads() expects a string, not a file object
    data = json.loads(file) 

Fix: Use json.load() for files and json.loads() for strings.

# CORRECT
with open('data.json', 'r') as file:
    data = json.load(file)

Summary

Function Purpose Example
json.load() Parses JSON from a file object. data = json.load(open('file.json'))
json.loads() Parses JSON from a string. data = json.loads('{"key": "value"}')
json.dump() Writes a Python object to a file object as JSON. json.dump(data, open('file.json', 'w'))
json.dumps() Converts a Python object to a JSON string. json_string = json.dumps(data)

For your request "python jason load", the correct function is json.load(), and it's used for reading JSON data from a file.

分享:
扫描分享到社交APP
上一篇
下一篇