Json简介:Json,全名 JavaScript Object Notation,是一种轻量级的数据交换格式。Json最广泛的应用是作为AJAX中web服务器和客户端的通讯的数据格式。现在也常用于http请求中,所以对json的各种学习,是自然而然的事情。
dumps方法
将字典数据类型转换为json字符串类型
例子:
import json
m = {‘a‘: 123, ‘b‘: ‘hahaha‘}
json_str = json.dumps(m)
print(json_str)
print(type(json_str))
输出:
{"a": 123, "b": "hahaha"}
<class ‘str‘>
Python格式对应Json格式
Python JSON
dict object
list, tuple array
str, unicode string
int, long, float number
True true
False false
None null
loads方法,将json格式转换为Python格式
例子:
import json
jsonData = ‘{"a":1,"b":2,"c":3}‘
dict1 = json.loads(jsonData)
print (dict1)
print (type(dict1))
输出:
{‘b‘: 2, ‘a‘: 1, ‘c‘: 3}
<class ‘dict‘>
dump方法,将Python数据类型的数据以Json格式写入文件
例子:
import json
jsonData = ‘{"a":1,"b":2,"c":3,"d":4,"e":5}‘
with open(‘a.txt‘, ‘w‘) as f:
json.dump(jsonData,f)
输出:
a.txt文件中写入内容
load方法,将Json类型的文件内容转换为Python数据格式读取
例子:
import json
jsonData = ‘{"a":1,"b":2,"c":3,"d":4,"e":5}‘
with open(‘a.txt‘, ‘w‘) as f:
json.dump(jsonData,f)
with open(‘a.txt‘, ‘r‘) as ff:
dict1=json.load(ff)
print(dict1)
print(type(dict1))
输出:
{"a":1,"b":2,"c":3,"d":4,"e":5}
<class ‘str‘>