1. 程式人生 > >Python進階 -- 4. 處理json檔案

Python進階 -- 4. 處理json檔案

1. 讀取【列表】格式的 json 檔案:
原始檔:

[
    {
            "Country Name": "Arab World",
            "Country Code": "ARB",
            "Year": "1960",
            "Value": "96388069"
    },
    {
            "Country Name": "Arab World",
            "Country Code": "ARB",
            "Year": "1961",
            "Value
": "98882541.4" } ]

程式碼:

import json

# 將資料載入到一個列表中
filename = '123.json'
with open(filename) as f:
    pop_data = json.load(f)

    # 列印每個國家2010年的人口數量
    for pop_dict in pop_data:
        country_name = pop_dict['Country Name']
        population = pop_dict['Value']
        print(country_name + ": "
+ population)

2. 讀取 {字典} 型別的 json 檔案:
原始檔:

{
     "fontFamily": "微軟雅黑",
     "fontSize": 12,
     "BaseSettings":{
         "font":1,
         "size":2
                    }
}

程式碼:

# 設定以utf-8解碼模式讀取檔案,encoding引數必須設定,否則預設以gbk模式讀取檔案,當檔案中包含中文時,會報錯
f = open("repositories.json", encoding='utf-8')
setting = json.load(f)

# 注意多重結構的讀取語法
family = setting['BaseSettings']['font'] style = setting['fontFamily'] print(family) print(style)

3. json模組的使用
- json: 用於字串和python資料型別間進行轉換
- Json模組提供了四個功能:dumps、dump、loads、load

json dumps把資料型別轉換成字串 dump把資料型別轉換成字串並存儲在檔案中 loads把字串轉換成資料型別 load把檔案開啟從字串轉換成資料型別

(1). dumps:將字典 轉換為 字串

import json

test_dict = {'bigberg': [7600, {1: [['iPhone', 6300], ['Bike', 800], ['shirt', 300]]}]}
print(test_dict)
print(type(test_dict))

#dumps 將資料轉換成字串
json_str = json.dumps(test_dict)
print(json_str)
print(type(json_str))

(2). dump: 將字典 轉換為 字串, 並寫入json檔案中

with open("../config/record.json","w") as f:
    json.dump(json_str,f)
    print("載入入檔案完成...")

(3). loads: 將 字串 轉換為 字典

new_dict = json.loads(json_str)
print(new_dict)
print(type(new_dict))

(4). load:把檔案開啟,並把字串變換為資料型別

with open("../config/record.json",'r') as load_f:
    load_dict = json.load(load_f)
    print(load_dict)

load_dict['smallberg'] = [8200,{1:[['Python',81],['shirt',300]]}]
print(load_dict)

with open("../config/record.json","w") as dump_f:
    json.dump(load_dict,dump_f)