Python标准库-JSON 文件操作

Python 的标准函数"json"提供了操作 JSON 文件的方法,可以针对 JSON 文件进行读取、写入或修改,这篇教程将会介绍 json 常用的方法。

JSON 是什么?

JSON ( JavaScript Object Notation ) 是一种 使用结构化数据呈现 JavaScript 对象的标准格式,也是相当普及的轻量级数据交换格式 ( JSON 本质只是纯文字格式 ),几乎所有与网络开发相关的语言都有处理 JSON 的函数库。

JSON 由"键"和"值"组成,可以在 JSON 里加入各种数据类型 ( 字符串、数字、数组、布尔值、对象、空值...等 ),下方是一个简单的 JSON 文件:

注意!标准 JSON 必须使用双引号 ( " ) 而不能使用单引号 ( ' ),否则在转换成 dict 类型时会发生错误

json 复制代码
{
  "name": "oxxo",
  "sex": "male",
  "age": 18,
  "phone": [
    {
      "type": "home",
      "number": "07 1234567"
    },
    {
      "type": "office",
      "number": "07 7654321"
    }
  ]
}

json 常用方法

下方列出几种 json 模块常用的方法:

方法 参数 说明
load() fp 读取本机 JSON 文件,并转换为 Python 的字典 dict 类型。
loads() s 将 JSON 格式的数据,转换为 Python 的字典 dict 类型。
dump() obj, fp 将字典 dict 类型的数据,写入本机 JSON 文件。
dumps() obj 将字典 dict 类型的数据转换为 JSON 格式的数据。
JSONDecoder()
将 JSON 格式的数据,转换为 Python 的字典 dict 类型。
JSONEncoder()
将字典 dict 类型的数据转换为 JSON 格式的数据。

import json

要使用 json 必须先 import json 模块,或使用 from 的方式,单独 import 特定的类型。

javascript 复制代码
import json
from json import load

load(fp)

json.load(fp) 会 读取本机 JSON 文件,并转换为 Python 的字典 dict 类型,JSON 数据在转换时,会按照下列表格的规则,转换为 Python 数据格式:

JSON Python
object 对象 dict 字典
array 数组 list 串列
string 文字/字符串 str 文字/字符串
number(int) 整数数字 int 整数
number(real) 浮点数字 float 浮点数
true True
false False
null None

下方的代码,会先 open 示例的 json 文件 ( 模式使用 r ),接着使用 json.load 读取该文件转换为 dict 类型,最后使用 for 循环将内容打打打打打打打打打打打打印出。

lua 复制代码
import json
jsonFile = open('./json-demo.json','r')
a = json.load(jsonFile)
for i in a:
    print(i, a[i])
'''
name oxxo
sex male
age 18
phone [{'type': 'home', 'number': '07 1234567'}, {'type': 'office', 'number': '07 7654321'}]
'''

loads(s)

json.loads(s) 能 将 JSON 格式的数据,转换为 Python 的字典 dict 类型 ,下方的例子,同样会先 open 示例的 json 文件 ( 模式使用 r ),接着使用 json.load 读取该文件转换为 dict 类型,最后使用 for 循环将内容打打打打打打打打打打打打印出 ( 用法上与 load 不太相同,load 读取的是文件,loads 是读取的是数据 )。

bash 复制代码
import json
jsonFile = open('./json-demo.json','r')
f =  jsonFile.read()   # 要先使用 read 读取文件
a = json.loads(f)      # 再使用 loads
for i in a:
    print(i, a[i])
'''
name oxxo
sex male
age 18
phone [{'type': 'home', 'number': '07 1234567'}, {'type': 'office', 'number': '07 7654321'}]
'''

dump(obj, fp)

json.dump(obj, fp) 能 将字典 dict 类型的数据转换成 JSON 格式,写入本机 JSON 文件,数据在转换时,会按照下列表格的规则,转换为 JSON 数据格式。

Python JSON
dict 字典 object 对象
list 数组、tuple 元组/数组 array 数组
str 文字/字符串 string 文字/字符串
int, float 各种数字 number 数字
True true
False false
None null

下方的代码,会先 open 示例的 json 文件 ( 模式使用 w ),接着编辑一个 data 的字典数据,完成后使用 dump 的方式将数据写入 json 文件中。

kotlin 复制代码
import json
jsonFile = open('./json-demo.json','w')
data = {}
data['name'] = 'oxxo'
data['age'] = 18
data['eat'] = ['apple','orange']
json.dump(data, jsonFile)

写入之后 JSON 文件的内容:

json 复制代码
{"name": "oxxo", "age": 18, "eat": ["apple", "orange"]}

如果设置" indent"可以将写入的数据进行缩排的排版。

kotlin 复制代码
import json
jsonFile = open('./json-demo.json','w')
data = {}
data['name'] = 'oxxo'
data['age'] = 18
data['eat'] = ['apple','orange']
json.dump(data, jsonFile, indent=2)

写入之后 JSON 文件的内容:

json 复制代码
{
  "name": "oxxo",
  "age": 18,
  "eat": [
    "apple",
    "orange"
  ]
}

dumps(obj)

json.dumps(obj) 能将字典 dict 类型的数据转换为 JSON 格式的数据,下方的例子,同样会先 open 示例的 json 文件 ( 模式使用 w ),接着使用 json.dumps 将 dict 字典的数据转换为 JSON 格式,最后使用 write 将数据写入 ( 用法上与 dump 不太相同,dump 转换数据并写入文件,dumps 只是转换数据 )。

kotlin 复制代码
import json
jsonFile = open('./json-demo.json','w')
data = {}
data['name'] = 'oxxo'
data['age'] = 18
data['eat'] = ['apple','orange']
w = json.dumps(data)     # 产生要写入的数据
jsonFile.write(w)        # 写入数据
jsonFile.close()

写入之后 JSON 文件的内容:

json 复制代码
{"name": "oxxo", "age": 18, "eat": ["apple", "orange"]}

然而 dumps 也可以单纯作为转换格式使用。

kotlin 复制代码
import json
jsonFile = open('./json-demo.json','r')
data = {}
data['name'] = 'oxxo'
data['age'] = 18
data['eat'] = ['apple','orange']
w = json.dumps(data)
print(w)
# {"name": "oxxo", "age": 18, "eat": ["apple", "orange"]}

JSONDecoder()

json.JSONDecoder() 会将 JSON 格式的数据,转换为 Python 的字典 dict 类型 ( json.load 和 json.loads 默认会使用 json.JSONDecoder() )。

kotlin 复制代码
import json
jsonFile = open('./json-demo.json','r')
data = jsonFile.read()
r = json.JSONDecoder().decode(data)
print(r)
# {'name': 'oxxo', 'age': 18, 'eat': ['apple', 'orange']}

JSONEncoder()

json.JSONEncoder() 会将字典 dict 类型的数据转换为 JSON 格式的数据 ( json.dump 和 json.dumps 默认会使用 json.JSONEncoder() )。

scss 复制代码
import json
data = {}
data['name'] = 'oxxo'
data['age'] = 18
data['eat'] = ['apple','orange']
w = json.JSONEncoder().encode(data)    # 使用 JSONEncoder() 的 encode 方法
print(w)
# {"name": "oxxo", "age": 18, "eat": ["apple", "orange"]}
相关推荐
王某某人2 分钟前
LangChain4j 入门:Java 程序员的第一个 AI 对话程序
人工智能·后端
码农刚子7 分钟前
从零开始:在 Windows 服务器上部署 Node.js 项目(小白实战教程)
后端·node.js
Cache技术分享7 分钟前
435. Java 日期时间 API - Clock 灵活获取当前时间
前端·后端
浩子coding16 分钟前
通过 Spring AI Alibaba 源码,看如何玩转 ReAct 智能体范式
人工智能·后端
星浩AI27 分钟前
合规项目大模型如何部署?硬件选型 + vLLM/LMDeploy 实战
pytorch·后端·llm
摇滚侠39 分钟前
SpringMVC 入门到实战 DispatcherServlet 源码解读 92-95
java·后端·spring·maven·intellij-idea
青山如墨雨如画42 分钟前
【北邮-无线通信中的人工智能】物理层技术中AI的应用实践:基于KNN的调制识别(1)理论基础
人工智能·python·机器学习·matlab·jupyter
MATLAB代码顾问1 小时前
Python Matplotlib数据可视化实战指南
python·信息可视化·matplotlib
AI 编程助手GPT1 小时前
用 Python 做一个世界杯赛前分析脚本:以巴西 vs 摩洛哥为例
开发语言·网络·人工智能·python·chatgpt
万事大吉CC1 小时前
Python 笔试输入模板总结
python·算法