飞翔飞翔
主页
  • 计算机基础

    • TCP/IP协议
    • Linux命令
  • 数据库

    • SQL教程
  • 编程语言

    • C语言
    • Python2
    • Python3
  • 数据格式

    • JSON教程
  • 工具

    • Markdown指南
  • Git

    • GitFlow
  • Quartz

    • Quartz教程
  • Java

    • Java设计模式
  • 缓存

    • Redis教程
联系
阿里云
主页
  • 计算机基础

    • TCP/IP协议
    • Linux命令
  • 数据库

    • SQL教程
  • 编程语言

    • C语言
    • Python2
    • Python3
  • 数据格式

    • JSON教程
  • 工具

    • Markdown指南
  • Git

    • GitFlow
  • Quartz

    • Quartz教程
  • Java

    • Java设计模式
  • 缓存

    • Redis教程
联系
阿里云
  • 学习路径
  • 第1章 认识Python

    • Python 历史与特点
    • Python 2 与 Python 3 的核心差异
    • 安装与运行 Python 2.7.18
    • 编码规范 PEP 8
  • 第2章 基础语法

    • 变量与对象
    • 数字类型
    • 字符串 str
    • Unicode 字符串
    • 运算符
    • 空值 None
  • 第3章 流程控制

    • if 条件语句
    • if-else 条件语句
    • if-elif-else 多分支
    • 条件表达式(三元运算符)
    • while 循环
    • for 循环
    • range 与 xrange
    • 循环控制:break、continue、pass
    • 循环 else 子句
  • 第4章 数据结构

    • 列表基础
    • 列表方法
    • 列表推导式
    • 元组
    • 字典基础
    • 字典方法
    • 字典循环技巧
    • 集合
    • 序列解包
    • 序列比较
  • 第5章 函数

    • 定义函数
    • 参数传递机制
    • 默认参数
    • 关键字参数
    • 可变参数
    • Lambda 表达式
    • 文档字符串
    • 函数对象
  • 第6章 模块与包

    • import 导入
    • 模块搜索路径
    • name 与主程序
    • 编译文件 .pyc 与 .pyo
    • 包结构
    • dir() 函数
  • 第7章 文件与IO

    • 打开与关闭文件
    • 文件读写方法
    • with 上下文管理器
    • 格式化输出:% 操作符
    • 格式化输出:str.format()
    • JSON 序列化
  • 第8章 面向对象

    • 类定义与实例化
    • init 构造方法
    • 类变量与实例变量
    • 方法调用与 self
    • 继承基础
    • 多重继承
    • 新式类与旧式类
    • 私有变量与名称改写
    • 属性装饰器 property
    • 类方法与静态方法
    • 魔术方法
    • 空类与数据记录
  • 第9章 异常处理

    • 异常类型
    • try-except
    • try-except-else-finally
    • 抛出异常 raise
    • 自定义异常
    • with 语句与上下文管理器
  • 第10章 迭代器与生成器

    • 迭代器协议
    • 生成器函数
    • 生成器表达式
    • itertools模块
  • 第11章 标准库精要

    • os模块
    • sys模块
    • datetime模块
    • re模块
    • json模块
    • collections模块
    • math与random模块
    • urllib2与网络请求
    • subprocess与命令执行
    • threading与并发
    • unittest与测试
    • 虚拟环境与包管理
  • 第12章 工程实践

    • 调试技巧
    • 性能分析
    • 文档与注释
    • 下一步学习

json模块

json 模块处理 JSON(JavaScript Object Notation)数据的编码和解码。JSON 是 Web 开发中最常用的数据交换格式,Python 的 json 模块让 Python 对象与 JSON 字符串之间的转换变得简单直接。

编码:Python → JSON

json.dumps:Python 对象 → JSON 字符串

import json

data = {
    "name": "Alice",
    "age": 30,
    "is_student": False,
    "courses": ["Math", "Physics"],
    "address": None
}

json_str = json.dumps(data)
print json_str
# {"name": "Alice", "age": 30, "is_student": false, "courses": ["Math", "Physics"], "address": null}

注意 JSON 与 Python 的类型差异:

PythonJSON
dictobject
list, tuplearray
str, unicodestring
int, long, floatnumber
Truetrue
Falsefalse
Nonenull

格式化输出:

print json.dumps(data, indent=2, ensure_ascii=False)
# {
#   "name": "Alice",
#   "age": 30,
#   "is_student": false,
#   "courses": [
#     "Math",
#     "Physics"
#   ],
#   "address": null
# }

indent 控制缩进,ensure_ascii=False 允许非 ASCII 字符直接输出(如中文)。

排序键:

print json.dumps(data, sort_keys=True)
# {"address": null, "age": 30, "courses": ["Math", "Physics"], "is_student": false, "name": "Alice"}

解码:JSON → Python

json.loads:JSON 字符串 → Python 对象

import json

json_str = '{"name": "Bob", "age": 25}'
data = json.loads(json_str)
print data              # {u'name': u'Bob', u'age': 25}
print type(data)        # <type 'dict'>
print data["name"]      # Bob

Python 2 中 JSON 字符串解码为 unicode 类型,而非 str。

从文件读取:

import json

with open("data.json", "r") as f:
    data = json.load(f)
    print data

写入文件:

import json

data = {"users": [{"name": "Alice"}, {"name": "Bob"}]}

with open("data.json", "w") as f:
    json.dump(data, f, indent=2)

处理自定义类型

JSON 默认不支持 Python 的 datetime、set 等类型:

import json
from datetime import datetime

data = {"time": datetime.now()}
# json.dumps(data)        # TypeError: datetime is not JSON serializable

自定义编码器:

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(CustomEncoder, self).default(obj)

data = {"time": datetime.now()}
print json.dumps(data, cls=CustomEncoder)
# {"time": "2024-01-15 14:30:25"}

自定义解码器:

import json
from datetime import datetime

def datetime_decoder(d):
    if "time" in d:
        d["time"] = datetime.strptime(d["time"], "%Y-%m-%d %H:%M:%S")
    return d

json_str = '{"time": "2024-01-15 14:30:25"}'
data = json.loads(json_str, object_hook=datetime_decoder)
print type(data["time"])    # <type 'datetime.datetime'>

实际应用

配置文件:

import json

def load_config(filename="config.json"):
    try:
        with open(filename, "r") as f:
            return json.load(f)
    except (IOError, ValueError):
        return {}

def save_config(config, filename="config.json"):
    with open(filename, "w") as f:
        json.dump(config, f, indent=2)

# 使用
config = load_config()
config["theme"] = "dark"
save_config(config)

API 响应处理:

import json
import urllib2

response = urllib2.urlopen("https://api.example.com/users")
data = json.load(response)

for user in data["users"]:
    print user["name"], user["email"]

数据缓存:

import json
import os

def cache_result(key, data, cache_dir="cache"):
    if not os.path.exists(cache_dir):
        os.makedirs(cache_dir)
    
    path = os.path.join(cache_dir, key + ".json")
    with open(path, "w") as f:
        json.dump(data, f)

def load_cache(key, cache_dir="cache"):
    path = os.path.join(cache_dir, key + ".json")
    if os.path.exists(path):
        with open(path, "r") as f:
            return json.load(f)
    return None

与 pickle 的区别

特性jsonpickle
格式文本,人类可读二进制
跨语言是否(仅 Python)
安全性安全不安全(不要加载不可信数据)
支持类型基本类型几乎所有 Python 对象
性能较慢较快
import json
import pickle

data = {"key": "value"}

# JSON:文本格式
print json.dumps(data)      # {"key": "value"}

# Pickle:二进制格式
print pickle.dumps(data)    # 不可读的二进制数据

Web 开发、配置文件、API 交互用 json。Python 对象持久化、进程间通信用 pickle(注意安全性)。

上一页
re模块
下一页
collections模块