python处理json文本文件主要是以下四个函数:
函数 | 作用 |
---|---|
json.dumps | 对数据进行编码,将python中的字典 转换为 字符串 |
json.loads | 对数据进行解码,将 字符串 转换为 python中的字典 |
json.dump | 将dict数据写入json文件中 |
json.load | 打开json文件,并把字符串转换为python的dict数据 |
json.dumps / json.loads
数据转换对照:
json | python |
---|---|
object | dict |
array | list |
string | str |
number (int) | int |
number (real) | float |
true | True |
false | False |
null | None |
代码示例:
import json tesdic = { \'name\': \'Tom\', \'age\': 18, \'score\': { \'math\': 98, \'chinese\': 99 } } print(type(tesdic)) json_str = json.dumps(tesdic) print(json_str) print(type(json_str)) newdic = json.loads(json_str) print(newdic) print(type(newdic))
输出为:
<class \'dict\'> {\"name\": \"Tom\", \"age\": 18, \"score\": {\"math\": 98, \"chinese\": 99}} <class \'str\'> {\'name\': \'Tom\', \'age\': 18, \'score\': {\'math\': 98, \'chinese\': 99}} <class \'dict\'>
json.dump / json.load
写入json的内容只能是dict类型,字符串类型的将会导致写入格式问题:
with open(\"res.json\", \'w\', encoding=\'utf-8\') as fw: json.dump(json_str, fw, indent=4, ensure_ascii=False)
则json文件内容为:
\"{\\\"name\\\": \\\"Tom\\\", \\\"age\\\": 18, \\\"score\\\": {\\\"math\\\": 98, \\\"chinese\\\": 99}}\"
我们换一种数据类型写入:
with open(\"res.json\", \'w\', encoding=\'utf-8\') as fw: json.dump(tesdic, fw, indent=4, ensure_ascii=False)
则生成的josn就是正确的格式:
{ \"name\": \"Tom\", \"age\": 18, \"score\": { \"math\": 98, \"chinese\": 99 } }
同理,从json中读取到的数据也是dict类型:
with open(\"res.json\", \'r\', encoding=\'utf-8\') as fw: injson = json.load(fw) print(injson) print(type(injson))
{\'name\': \'Tom\', \'age\': 18, \'score\': {\'math\': 98, \'chinese\': 99}} <class \'dict\'>
总结
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注的更多内容!
© 版权声明
THE END
暂无评论内容