标签:数据类型 类型 out als .json 学院 pytho 使用 json
用于序列化的两个模块
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‘> {‘北京市‘: {‘朝阳区‘: [‘三里屯‘, ‘望京‘, ‘国贸‘], ‘海淀区‘: [‘五道口‘, ‘学院路‘, ‘后厂村‘], ‘东城区‘: [‘东直门‘, ‘崇文门‘, ‘王府井‘]}, ‘上海市‘: {‘静安区‘: [], ‘黄浦区‘: [], ‘虹口区‘: []}}
标签:数据类型 类型 out als .json 学院 pytho 使用 json
原文地址:http://www.cnblogs.com/jmaly/p/7645611.html