python json & pickle 模块
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python json & pickle 模块相关的知识,希望对你有一定的参考价值。
用于序列化的两个模块
- json,用于字符串 和 python数据类型间进行转换
- pickle,用于python特有的类型 和 python的数据类型间进行转换
Json模块提供了四个功能:dumps、dump、loads、load
pickle模块提供了四个功能:dumps、dump、loads、load
"""
python 3 JSON模块使用
"""
import json
data = {
"北京市": {
"朝阳区": ["三里屯", "望京", "国贸"],
"海淀区": ["五道口", "学院路", "后厂村"],
"东城区": ["东直门", "崇文门", "王府井"],
},
"上海市": {
"静安区": [],
"黄浦区": [],
"虹口区": [],
}
}
1、json.dumps dict-->strting
s_dumps = json.dumps(data, sort_keys=True, indent=4, ensure_ascii=False) print(type(s_dumps)) print(s_dumps) output: <class ‘str‘> { "上海市": { "虹口区": [], "静安区": [], "黄浦区": [] }, "北京市": { "东城区": [ "东直门", "崇文门", "王府井" ], "朝阳区": [ "三里屯", "望京", "国贸" ], "海淀区": [ "五道口", "学院路", "后厂村" ] } }
2、json.loads string-->dict
r_loads = json.loads(s_dumps) print(type(r_loads)) print(r_loads) output: <class ‘dict‘> {‘上海市‘: {‘虹口区‘: [], ‘静安区‘: [], ‘黄浦区‘: []}, ‘北京市‘: {‘东城区‘: [‘东直门‘, ‘崇文门‘, ‘王府井‘], ‘朝阳区‘: [‘三里屯‘, ‘望京‘, ‘国贸‘], ‘海淀区‘: [‘五道口‘, ‘学院路‘, ‘后厂村‘]}}
3、json.dump 写入文件
with open("data.json", "w", encoding="UTF-8") as f_dump:
s_dump = json.dump(data, f_dump, indent=4, ensure_ascii=False)
4、json.load 从文件读取
with open("data.json", "r", encoding="utf-8") as f_load: r_load = json.load(f_load) print(type(r_load)) print(r_load) output: <class ‘dict‘> {‘北京市‘: {‘朝阳区‘: [‘三里屯‘, ‘望京‘, ‘国贸‘], ‘海淀区‘: [‘五道口‘, ‘学院路‘, ‘后厂村‘], ‘东城区‘: [‘东直门‘, ‘崇文门‘, ‘王府井‘]}, ‘上海市‘: {‘静安区‘: [], ‘黄浦区‘: [], ‘虹口区‘: []}}
以上是关于python json & pickle 模块的主要内容,如果未能解决你的问题,请参考以下文章
python序列化: json & pickle & shelve 模块
Python json & pickle & shelve模块