python中json.dump()与json.dumps()的区别
1.将python数据结构转换为json字符串(json.dumps())
>>> import json >>> data={'name':'pipi','age':18} >>> json.dumps(data) '{"name": "pipi", "age": 18}'
2.将json格式的字符串转换为python数据结构(json.loads())
>>> json_str='{"name": "pipi", "age": 18}' >>> json.loads(json_str) {'name': 'pipi', 'age': 18}
3.将json对象写入文件中(json.dump())
data={'name':'pipi','age':18} >>> with open("c:/Users/cale/json.txt",'w') as f: json.dump(data,f)
4.从文件中获取json对象
with open("c:/Users/cale/json.txt",'r') as f: data=json.load(f) >>> data {'name': 'pipi', 'age': 18} >>>
注:如果用f.read()获取的是一个字符串,而不是json对象
with open("c:/Users/cale/json.txt",'r') as f: data=f.read() >>> data '{"name": "pipi", "age": 18}'
备注:json格式的数据不一定是字典对象,也可以是列表,字符串(列表及字符串都可以用json.loads()方法解析)。如下:
>>> m='[1,2,3]'
>>> import json
>>> json.loads(m)
[1, 2, 3]
>>> m='123'
>>> json.loads(m)
123
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
把一个列表类型的字符串转换成列表有两张方法:
1.
eval('[1,2,3]')
[1, 2, 3]
2.
json.loads('[1,2,3]')
[1, 2, 3]