1. 导入Json
import json
2. 常用函数
json.dumps() | 将python数据类型 (list, dict) 转换成json格式的字符串 |
json.dump() | 讲python数据类型转换 (list, dict) 并保存到json格式的文件内 |
json.loads() | 将json格式的字符串转换为python数据类型 (list, dict) |
json.load() | 从json文件读取数据并转换为python数据类型 (list, dict) |
3. 示例及结果
json.dumps():将python中的 dict 转换成 json string
示例:
import json
dict_person = {
'name': 'Aaron',
'age': 20,
'email': ['12345@qq.com', '34567@163.com'],
'is_stu': True
}
json_person = json.dumps(dict_person)
print(dict_person, type(dict_person))
print(json_person, type(json_person))
结果:注意 -> dict 和 json string 的区别- boolean值以及单双引号
json.dump() :相对于json.dumps来说是增加了保存到json文件的操作
示例:
with open('test.json', 'w') as f:
json.dump(dict_person, f)
结果:test.json文件下的内容 ↓
json.loads(): 将json string转换成python格式
示例:
json_str = '{"name": "Aaron","age": 20,"email": ["12345@qq.com", "34567@163.com"],"is_stu": true}'
python_dict = json.loads(json_str)
print(json_str, type(json_str))
print(python_dict, type(python_dict))
json_str1 = '["Aaron", "neil", "best"]'
python_dict1 = json.loads(json_str1)
print(json_str1, type(json_str1))
print(python_dict1, type(python_dict1))
结果:
json.load() : 从test.json读取数据并转换为dict
示例:
with open('test.json', 'r') as f:
python_dict = json.load(f)
print(python_dict, type(python_dict))
结果:
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/87479.html