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"]}
相关推荐
风象南9 分钟前
普通人用AI加持赚到的第一个100块
人工智能·后端
冰_河2 小时前
QPS从300到3100:我靠一行代码让接口性能暴涨10倍,系统性能原地起飞!!
java·后端·性能优化
JavaGuide4 小时前
7 道 RAG 基础概念知识点/面试题总结
前端·后端
桦说编程5 小时前
从 ForkJoinPool 的 Compensate 看并发框架的线程补偿思想
java·后端·源码阅读
孟健5 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
格砸6 小时前
从入门到辞职|从ChatGPT到OpenClaw,跟上智能时代的进化
前端·人工智能·后端
蝎子莱莱爱打怪6 小时前
GitLab CI/CD + Docker Registry + K8s 部署完整实战指南
后端·docker·kubernetes
哈密瓜的眉毛美6 小时前
零基础学Java|第三篇:DOS 命令、转义字符、注释与代码规范
后端
用户60572374873087 小时前
AI 编码助手的规范驱动开发 - OpenSpec 初探
前端·后端·程序员