杰瑞科技汇

Python中json.loads()如何使用?

Of course! Let's break down json.loads() in Python, from the basics to practical examples.

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

What is json.loads()?

json.loads() is a Python function that stands for "load string". Its primary job is to parse a string that contains JSON data and convert it into a corresponding Python object.

Think of it as a decoder. It takes a JSON-formatted string and translates it into Python's native data types.


The Key Concept: JSON vs. Python Data Types

To understand json.loads(), you first need to know how JSON data types map to Python data types.

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

This mapping is the "magic" behind json.loads(). It correctly translates the JSON syntax into the appropriate Python objects.

Python中json.loads()如何使用?-图2
(图片来源网络,侵删)

How to Use json.loads()

The Basic Syntax

First, you need to import the json module, which is part of Python's standard library (no installation needed).

import json
# The function is called like this:
# python_object = json.loads(json_string)

A Simple Example

Let's start with a basic JSON string representing a person.

import json
# A string containing JSON data
json_string = '{"name": "Alice", "age": 30, "isStudent": false, "courses": ["History", "Math"]}'
# Use json.loads() to convert the string to a Python dictionary
python_dict = json.loads(json_string)
# Now, python_dict is a native Python object
print(f"Type of the result: {type(python_dict)}")
print(f"Result: {python_dict}")
# You can access its data just like a regular dictionary
print(f"Name: {python_dict['name']}")
print(f"First course: {python_dict['courses'][0]}")

Output:

Type of the result: <class 'dict'>
Result: {'name': 'Alice', 'age': 30, 'isStudent': False, 'courses': ['History', 'Math']}
Name: Alice
First course: History

Notice how false became False and the array became a list.

Python中json.loads()如何使用?-图3
(图片来源网络,侵删)

Handling Common Errors

json.loads() is strict. If the input string is not perfectly valid JSON, it will raise a json.JSONDecodeError exception.

json.JSONDecodeError (Most Common)

This happens if the string is malformed.

import json
# Invalid JSON: missing a comma
invalid_json_string = '{"name": "Bob" "age": 25}'
try:
    python_dict = json.loads(invalid_json_string)
except json.JSONDecodeError as e:
    print(f"Error decoding JSON: {e}")

Output:

Error decoding JSON: Expecting ',' delimiter: line 1 column 14 (char 13)

TypeError

This happens if you pass something other than a string (or bytes-like object) to the function.

import json
# Trying to load a Python dictionary directly (not a string)
python_dict = {"name": "Charlie"}
try:
    # This will fail because json.loads() expects a string
    result = json.loads(python_dict)
except TypeError as e:
    print(f"Error: {e}")
# The correct way is to first convert the dict to a JSON string using json.dumps()
json_string = json.dumps(python_dict)
print(f"Correctly converted string: {json_string}")
# Now you can load it
result = json.loads(json_string)
print(f"Successfully loaded: {result}")

Output:

Error: the JSON object must be str, bytes or bytearray, not dict
Correctly converted string: {"name": "Charlie"}
Successfully loaded: {'name': 'Charlie'}

json.loads() vs. json.load() (A Crucial Distinction)

This is a very common point of confusion for beginners.

Function What it does Input Example
json.loads() Loads from String Parses a string containing JSON. json.loads('{"key": "value"}')
json.load() Loads from a file-like object Parses a file object (opened in text mode) or a text stream. json.load(open('data.json'))

Analogy:

  • loads() is like reading a recipe written on a sticky note.
  • json.load() is like reading a recipe from a cookbook.

Example of json.load():

Imagine you have a file named data.json:

{
  "city": "New York",
  "population": 8400000
}

Here's how you would read it using json.load():

import json
# Open the file in read mode ('r')
with open('data.json', 'r') as file:
    # json.load() reads from the file object
    data = json.load(file)
print(data)
print(f"Type: {type(data)}")

Output:

{'city': 'New York', 'population': 8400000}
Type: <class 'dict'>

Real-World Use Case: Handling API Responses

A very common use case for json.loads() is processing data received from a web API. APIs almost always send data as a JSON string.

import json
import requests # A popular library for making HTTP requests
# Simulate an API response (in a real app, this would come from an API call)
api_response_string = '''
{
  "status": "success",
  "data": {
    "userId": 123,
    "username": "api_user",
    "permissions": ["read", "write"]
  }
}
'''
# Parse the JSON string from the API response
response_data = json.loads(api_response_string)
# Now you can easily work with the data
if response_data['status'] == 'success':
    user_info = response_data['data']
    print(f"User {user_info['username']} (ID: {user_info['userId']}) has permissions: {user_info['permissions']}")

Output:

User api_user (ID: 123) has permissions: ['read', 'write']

Summary

Function Purpose Input Output
json.loads() Parse a JSON string. str Python objects (dict, list, etc.)
json.load() Parse a JSON file object. File object Python objects (dict, list, etc.)
json.dumps() Dump a Python object to a JSON string. Python object str
json.dump() Dump a Python object to a JSON file. Python object & File object Writes to a file

Remember: loads() is for strings, load() is for files. This is the most important takeaway.

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