Python基础之JSON

24次阅读

共计 549 个字符,预计需要花费 2 分钟才能阅读完成。

作用

对 Python 对象进行序列化,便于存储和传输

Python 对象与 JSON 字符串相互转换

Python 对象转 JSON 字符串

import json
data = [{ 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5} ]
json_str = json.dumps(data, ensure_ascii=False)  # 设置 ensure_ascii=False 以支持中文
print(type(json_str))
print(json_str)

结果是
<class 'str'>
[{"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}]

JSON 字符串转 Python 对象

import json
json_str = '[{"a": 1,"b": 2,"c": 3,"d": 4,"e": 5}]'
data = json.loads(json_str)
print(type(data))
print(data)

结果是
<class 'list'>
[{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}]

Python 对象通过 JSON 往文件读写

Python 对象可与 JSON 字符串相互转换,字符串往文件读写按正常的就行了

想进一步了解编程开发相关知识,与我一同成长进步,请关注我的公众号“松果仓库”,共同分享宅 & 程序员的各类资源,谢谢!!!

正文完
 0