python的json模块中dumps和loads、dump和load
import json
data = {1:'a', 2:'b', 3:'c'} # 数据
1. dumps和loads
注意: dumps和loads不仅仅对字典起作用
-
dumps(), 将
python对象
转换为josn字符串
res1 = json.dumps(data) print(res1, type(res1))
{"1": "a", "2": "b", "3": "c"} <class 'str'>
Python Json dict object list, tuple array str, unicode string int, long, float number True true False false None null -
loads(), 将
josn字符串
转换为python对象
res2 = json.loads(res1) print(res2, type(res2))
{'1': 'a', '2': 'b', '3': 'c'} <class 'dict'>
Json Python object dict array list string unicode number(int) int, long number(real) float true True false False null None
2. dump和load
注意: dumps和loads是作用在python对象
和josn字符串
上的, 而dump和load是作用在json文件
上的
-
dump, 将数据以json的格式保存至文件
with open('file', 'w') as f: json.dump(data, f)
-
load, 读取json文件
with open('file', 'r') as f: res3 = json.load(f) print(res3, type(res3))
{'1': 'a', '2': 'b', '3': 'c'} <class 'dict'>
分析: 此处数据data
为python字典, 使用json保存并读取后亦为字典; 若数据为python字符串对象使用dump保存, 则使用load读取后亦为字符串(可进一步通过loads将字符串转换为python对象)。
with open('file', 'w') as f:
json.dump(res1, f)
with open('file', 'r') as f:
res3 = json.load(f)
print(res3, type(res3))
print('*'*50)
res4 = json.loads(res3)
print(res4, type(res4))
{"1": "a", "2": "b", "3": "c"} <class 'str'>
**************************************************
{'1': 'a', '2': 'b', '3': 'c'} <class 'dict'>
彩蛋
细心的同学可能发现, 在使用dumps(),将python对象
转换为josn字符串
后, 原本数据data
的key
为int
类型变成了字符串类型。注意json字符串
和python字符串
的区别, 如以下报错:
str1 = '{1:"a", 2:"b", 3:"c"}'
print(str1, type(str1))
res5 = json.loads(str1)
print(res5, type(res5))
{1:"a", 2:"b", 3:"c"} <class 'str'>
.......
JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
还需要注意的一点是, json字符串
的内部为双引号(""
), 否则也会报以上错误
因此, 构建json字符串
时需要特别注意, 正确构建方式如下:
str1 = '{"1":"a", "2":"b", "3":"c"}'
print(str1, type(str1))
res5 = json.loads(str1)
print(res5, type(res5))
{"1":"a", "2":"b", "3":"c"} <class 'str'>
{'1': 'a', '2': 'b', '3': 'c'} <class 'dict'>