杰瑞科技汇

Python json loads 如何正确使用?

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

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

Let's break it down.

What is json.loads()?

  • json: This is Python's built-in module for working with JSON (JavaScript Object Notation) data.
  • .loads(): This stands for "load string". Its job is to take a string that contains JSON data and convert it into a corresponding Python object.

Think of it as a decoder. It decodes a JSON string into a Python-native format.


The Core Concept: JSON vs. Python

json.loads() works by mapping JSON data types to Python data types.

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

This mapping is the key to understanding how json.loads() works.

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

How to Use json.loads()

Here is a step-by-step guide with examples.

Step 1: Import the json Module

First, you need to import the library. It's built-in, so you don't need to install anything.

import json

Step 2: Create a JSON String

Your input must be a string. It's a common mistake to pass a dictionary directly. Notice the single quotes around the whole structure, which makes it a string in Python.

json_string = '{"name": "Alice", "age": 30, "isStudent": false, "courses": ["History", "Math"]}'

Note: The boolean false and null in JSON are valid inside a JSON string. Python will convert them to False and None.

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

Step 3: Load the String into a Python Object

Use json.loads() and pass your JSON string to it. The result is stored in a Python variable.

python_object = json.loads(json_string)

Step 4: Use the Result

Now, python_object is a standard Python dictionary and list. You can access its data just like you normally would.

# Access dictionary values using keys
print(python_object['name'])        # Output: Alice
print(python_object['age'])         # Output: 30
print(python_object['isStudent'])   # Output: False
# Access list items
print(python_object['courses'][0])  # Output: History
print(python_object['courses'][1])  # Output: Math
# You can even use methods on the resulting objects
print(type(python_object))          # Output: <class 'dict'>
print(type(python_object['courses']))# Output: <class 'list'>

Complete Example

Here is a full, runnable example.

import json
# 1. A sample JSON string (e.g., from a web API or a file)
json_data_string = '''
{
  "id": 101,
  "product": "Laptop",
  "price": 1200.50,
  "in_stock": true,
  "specs": {
    "cpu": "Intel i7",
    "ram": 16
  },
  "tags": ["electronics", "computers"]
}
'''
# 2. Use json.loads() to convert the string to a Python object
try:
    python_dict = json.loads(json_data_string)
    # 3. Now, work with the Python dictionary
    print("--- Successfully loaded JSON string ---")
    print(f"Product Name: {python_dict['product']}")
    print(f"Price: ${python_dict['price']}")
    print(f"Is it in stock? {python_dict['in_stock']}")
    # Accessing a nested dictionary
    print(f"CPU: {python_dict['specs']['cpu']}")
    # Accessing a list within the dictionary
    print(f"Tags: {python_dict['tags']}")
    print(f"First tag: {python_dict['tags'][0]}")
    print("\n--- Type of the final object ---")
    print(type(python_dict))
except json.JSONDecodeError as e:
    print(f"Error decoding JSON: {e}")

Common Errors and How to Fix Them

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

Error 1: Trailing Commas

JSON does not allow trailing commas in objects or arrays.

# INCORRECT JSON STRING
bad_json_string = '{"name": "Bob", "age": 40,}' # The comma after 40 is invalid
try:
    json.loads(bad_json_string)
except json.JSONDecodeError as e:
    print(f"Caught an error: {e}")
    # Output: Caught an error: Expecting property name enclosed in double quotes: line 1 column 20 (char 19)

Solution: Remove the trailing comma.

Error 2: Single Quotes for Keys

JSON requires double quotes () around keys and string values. Python dictionaries can use single quotes (), but JSON cannot.

# INCORRECT JSON STRING (uses single quotes)
bad_json_string = "{'name': 'Charlie', 'city': 'New York'}"
try:
    json.loads(bad_json_string)
except json.JSONDecodeError as e:
    print(f"Caught an error: {e}")
    # Output: Caught an error: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

Solution: Replace all single quotes around keys and string values with double quotes.

# CORRECT JSON STRING
good_json_string = '{"name": "Charlie", "city": "New York"}'
python_object = json.loads(good_json_string)
print(python_object['name']) # Output: Charlie

The Opposite: json.dumps()

It's very common to use json.loads() with its counterpart, json.dumps().

  • json.loads(): Load a string -> Decode JSON to Python.
  • json.dumps(): Dump (serialize) a Python object -> Encode Python to a JSON string.
import json
# A Python dictionary
python_data = {
    "user": "Diana",
    "scores": [98, 87, 92],
    "active": True
}
# Convert the Python object back to a JSON string
json_string_output = json.dumps(python_data)
print(json_string_output)
# Output: {"user": "Diana", "scores": [98, 87, 92], "active": true}

Summary

Function What it Does Input Output Use Case
json.loads() Loads from a string A JSON formatted string A Python object (dict, list, etc.) Reading data from a file, an API response, or a user input that is a string.
json.dumps() Dumps to a string A Python object (dict, list, etc.) A JSON formatted string Preparing data to be sent to a web API, written to a file, or displayed.
分享:
扫描分享到社交APP
上一篇
下一篇