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"]}
相关推荐
gavin carter1 分钟前
gitHub hexo 个人博客升级版
python·github·hexo
Hanbox1 分钟前
FastAPI+Django构建全栈性能怪兽
后端
LucianaiB5 分钟前
智能体还能配置MCP?手把手用百宝箱打造一个音途智游,让旅游加入语音
后端
海风极客23 分钟前
《Go小技巧&易错点100例》第三十五篇
开发语言·后端·golang
武子康30 分钟前
大数据-10-HDFS集群 Java实现MapReduce WordCount计算 Hadoop序列化 编写Mapper和Reducer和Driver 附带PO
大数据·后端
我是哪吒36 分钟前
分布式微服务系统架构第147集:JavaPlus技术文档平台日更
后端·面试·github
社会零时工1 小时前
【python】基于pycharm的海康相机SDK二次开发
python·opencv·pycharm·相机
火车叼位1 小时前
从 pip 到 pipx:隔离、轻量、跨平台的 Python 工具管理
python
Nick同学1 小时前
原生 PHP 操作数据库的方式
数据库·后端·php
neoooo1 小时前
SQL中JOIN操作的条件使用总结与最佳实践
java·后端·mysql