ai
  • index
  • cursor
  • vector
  • crawl
  • crawl-front
  • DrissionPage
  • logging
  • mysql
  • pprint
  • sqlalchemy
  • contextmanager
  • dotenv
  • Flask
  • python
  • job
  • pdfplumber
  • python-docx
  • redbook
  • douyin
  • ffmpeg
  • json
  • numpy
  • opencv-python
  • pypinyin
  • re
  • requests
  • subprocess
  • time
  • uuid
  • watermark
  • milvus
  • pymilvus
  • search
  • Blueprint
  • flash
  • Jinja2
  • secure_filename
  • url_for
  • Werkzeug
  • chroma
  • HNSW
  • pillow
  • pandas
  • beautifulsoup4
  • langchain-community
  • langchain-core
  • langchain
  • langchain_unstructured
  • libreoffice
  • lxml
  • openpyxl
  • pymupdf
  • python-pptx
  • RAGFlow
  • tabulate
  • sentence_transformers
  • jsonl
  • collections
  • jieba
  • rag_optimize
  • rag
  • rank_bm25
  • Hugging_Face
  • modelscope
  • all-MiniLM-L6-v2
  • ollama
  • rag_measure
  • ragas
  • ASGI
  • FastAPI
  • FastChat
  • Jupyter
  • PyTorch
  • serper
  • uvicorn
  • markdownify
  • NormalizedLevenshtein
  • raq-action
  • CrossEncoder
  • Bi-Encoder
  • neo4j
  • neo4j4python
  • matplotlib
  • Plotly
  • Streamlit
  • py2neo
  • abc
  • read_csv
  • neo4jinstall
  • APOC
  • neo4jproject
  • uv
  • GDS
  • heapq
  • 1. 基本功能
    • 主要函数
  • 2. 基本使用
    • 编码(Python → JSON)
    • 解码(JSON → Python)
  • 3. 文件操作
    • 写入JSON文件
    • 读取JSON文件
  • 4. 数据类型对应关系
  • 5. 高级用法
    • 自定义编码器
    • 处理复杂对象
  • 6. 参数说明
    • dumps/dump常用参数
    • loads/load常用参数
  • 7. 实际应用示例
    • API响应处理
    • 配置文件读写
    • 数据持久化
  • 8. 注意事项

JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,Python中的json模块提供了JSON数据的编码(序列化)和解码(反序列化)功能。

1. 基本功能 #

主要函数 #

函数 描述
json.dumps() 将Python对象编码为JSON字符串
json.loads() 将JSON字符串解码为Python对象
json.dump() 将Python对象编码并写入文件
json.load() 从文件读取并解码为Python对象

2. 基本使用 #

编码(Python → JSON) #

import json

# Python字典
data = {
    "name": "张三",
    "age": 30,
    "married": True,
    "children": ["小明", "小红"],
    "pets": None
}

# 转换为JSON字符串
json_str = json.dumps(data, ensure_ascii=False, indent=4)
print(json_str)

输出:

{
    "name": "张三",
    "age": 30,
    "married": true,
    "children": ["小明", "小红"],
    "pets": null
}

解码(JSON → Python) #

# JSON字符串
json_data = '{"name": "李四", "age": 25, "city": "北京"}'

# 转换为Python字典
python_dict = json.loads(json_data)
print(python_dict["name"])  # 输出:李四

3. 文件操作 #

写入JSON文件 #

data = {"name": "王五", "score": 95.5}

with open("data.json", "w", encoding="utf-8") as f:
    json.dump(data, f, ensure_ascii=False, indent=2)

读取JSON文件 #

with open("data.json", "r", encoding="utf-8") as f:
    loaded_data = json.load(f)

print(loaded_data)  # 输出:{'name': '王五', 'score': 95.5}

4. 数据类型对应关系 #

Python类型 JSON类型
dict object
list, tuple array
str string
int, float number
True true
False false
None null

5. 高级用法 #

自定义编码器 #

import json
from datetime import datetime

class CustomEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.strftime("%Y-%m-%d %H:%M:%S")
        return super().default(obj)

data = {
    "event": "会议",
    "time": datetime.now()
}

json_str = json.dumps(data, cls=CustomEncoder, ensure_ascii=False)
print(json_str)

处理复杂对象 #

def decode_complex(dct):
    if "__complex__" in dct:
        return complex(dct["real"], dct["imag"])
    return dct

json_str = '{"__complex__": true, "real": 1, "imag": 2}'
data = json.loads(json_str, object_hook=decode_complex)
print(data)  # 输出:(1+2j)

6. 参数说明 #

dumps/dump常用参数 #

  • ensure_ascii: 默认为True,非ASCII字符会被转义;设为False可保留原字符
  • indent: 缩进空格数,用于美化输出
  • sort_keys: 设为True时字典按键排序
  • separators: 控制分隔符,如(',', ': ')

loads/load常用参数 #

  • object_hook: 用于自定义解码函数
  • parse_float: 指定浮点数解码函数
  • parse_int: 指定整数解码函数

7. 实际应用示例 #

API响应处理 #

import json
import requests

response = requests.get("https://api.example.com/data")
data = json.loads(response.text)
print(data["results"][0])

配置文件读写 #

# 写入配置
config = {"theme": "dark", "font_size": 14}
with open("config.json", "w") as f:
    json.dump(config, f, indent=2)

# 读取配置
with open("config.json", "r") as f:
    loaded_config = json.load(f)

数据持久化 #

class User:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def to_json(self):
        return json.dumps(self.__dict__)

    @classmethod
    def from_json(cls, json_str):
        data = json.loads(json_str)
        return cls(**data)

user = User("赵六", 28)
json_data = user.to_json()
new_user = User.from_json(json_data)

8. 注意事项 #

  1. JSON的键必须是字符串类型(Python中可以是任何可哈希类型,但转换为JSON时会转为字符串)
  2. 不是所有的Python对象都可以直接序列化为JSON(如自定义类的实例)
  3. 处理大量数据时,考虑使用ijson等流式处理库
  4. 确保JSON文件使用UTF-8编码,特别是包含非ASCII字符时

json模块简单易用,是Python中处理JSON数据的标准方式,适用于配置文件、Web API交互、数据存储等多种场景。

访问验证

请输入访问令牌

Token不正确,请重新输入