Json数据就是字符串,可以表示Python中数据;Json数据已键值对形式进行存储,数据必须用双引号(" ")括起;
数据对比:
Python json
dict object
list/tuple 数组
str str
int/float 数字
True/False true/false
None null
代码:
import json
data = {
'name':'renxin',
'age':20,
'lis':[1,2,3,4,5],
'tu':(1,2,3,4,5),
'bo':True,
'n':None
} #python对象
#dumps 将Python对象转换为json对象(序列化过程)
d_j = json.dumps(data) #
#loads 将json对象转换为Python对象(反序列化过程)
d_p = json.loads(d_j) #
#文件操作 dump将Python对象转换为json对象(序列化过程)
with open('j_test','w+')as f:
json.dump(data,f)
f.seek(0)
content = f.read()
#文件操作 load将Python对象转换为json对象(序列化过程)
with open('j_test','r')as f:
a = json.load(f)
print(json.__all__ ) #查看json模块中所有方法
print(content) #文件操作dump结果
print(a) #文件操作load结果
#运行结果
"""
['dump', 'dumps', 'load', 'loads', 'JSONDecoder', 'JSONDecodeError', 'JSONEncoder']
{"name": "renxin", "age": 20, "lis": [1, 2, 3, 4, 5], "tu": [1, 2, 3, 4, 5], "bo": true, "n": null}
{'name': 'renxin', 'age': 20, 'lis': [1, 2, 3, 4, 5], 'tu': [1, 2, 3, 4, 5], 'bo': True, 'n': None}
"""