如何将Python对象转换成json字符串:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import json persons = [ { 'username':'qiubai', 'age':18, 'country':'china' }, { 'username':'hello', 'age':17, 'country':'asia' } ] json_str = json.dumps(persons) #使用dumps函数可以把列表中的元素转换成json字符串 print(type(json_str)) print(json_str) |


在json.cn里可以正常解析,就说明这是一个json字符串
注意只有Python的基本数据类型才能转换成json字符串
存储json字符串到文件中:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import json persons = [ { 'username':'qiubai', 'age':18, 'country':'china' }, { 'username':'hello', 'age':17, 'country':'asia' } ] #使用dump函数将字符串直接写入json文件中 with open("persons.json","w") as fp: json.dump(persons,fp) |

当遇到需要存储中文的时候,需要关闭ascii码存储,并且指定文件的编码
如果不关闭ascii码存储中文就会存储成ascii码
1 2 |
with open("persons.json","w",encoding="utf-8") as fp: json.dump(persons,fp,ensure_ascii=False) |
