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)

你可能感兴趣的:(Python)