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"]}
相关推荐
zzzyulin34 分钟前
huggingface transformers调试问题--加载本地路径模型时pdb断点消失
python·transformer
用户685453759776935 分钟前
🔥 服务熔断降级:微服务的"保险丝"大作战!
后端
Tech有道35 分钟前
拼多多「面试官问我:LRU 和 LFU 你选谁?」我:看场景啊哥!😂
后端
用户685453759776935 分钟前
🎬 开场:RPC框架的前世今生
后端
教练、我想打篮球37 分钟前
12 pyflink 的一个基础使用, 以及环境相关
python·flink·pyflink
王中阳Go背后的男人40 分钟前
Docker磁盘满了?这样清理高效又安全
后端·docker
用户685453759776941 分钟前
🎛️ 分布式配置中心:让配置管理不再是噩梦!
后端
CodeFans41 分钟前
Spring 浅析
后端
李广坤43 分钟前
Filter(过滤器)、Interceptor(拦截器) 和 AOP(面向切面编程)
后端
oak隔壁找我44 分钟前
反向代理详解
后端·架构