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"]}
相关推荐
再努力"亿"点点1 天前
Sklearn(机器学习)实战:鸢尾花数据集处理技巧
开发语言·python
lizhongxuan1 天前
Spec-Kit 使用指南
后端
费弗里1 天前
无需云服务器!通过Plotly Cloud免费快捷部署Dash应用
python·dash
跟橙姐学代码1 天前
轻松搞定 Python 模块与包导入:新手也能秒懂的入门指南
前端·python·ipython
会豪1 天前
工业仿真(simulation)--发生器,吸收器,缓冲区(2)
后端
SamDeepThinking1 天前
使用Cursor生成【财务对账系统】前后端代码
后端·ai编程·cursor
饭碗的彼岸one1 天前
C++ 并发编程:异步任务
c语言·开发语言·c++·后端·c·异步
荏苒追寻1 天前
Python 爬虫——爬虫基础
python
会豪1 天前
工业仿真(simulation)--仿真引擎,离散事件仿真(1)
后端
Java微观世界1 天前
匿名内部类和 Lambda 表达式为何要求外部变量是 final 或等效 final?原理与解决方案
java·后端