1. 程式人生 > >python json & pickle 模塊

python json & pickle 模塊

文件讀取 python pickle 朝陽區 字符 span 進行 als put

用於序列化的兩個模塊

  • 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 模塊