Python进阶 -- 4. 处理json文件(转载)

https://blog.csdn.net/lwbeyond/article/details/61198555源地址

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"
    }
]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
代码:
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)
1
2
3
4
5
6
7
8
9
10
11
12


2. 读取 {字典} 类型的 json 文件: 
源文件:
{
     "fontFamily": "微软雅黑",
     "fontSize": 12,
     "BaseSettings":{
         "font":1,
         "size":2
                    }
}
1
2
3
4
5
6
7
8
代码:
# 设置以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)
1
2
3
4
5
6
7
8
9
10


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))
1
2
3
4
5
6
7
8
9
10
(2). dump: 将字典 转换为 字符串, 并写入json文件中
with open("../config/record.json","w") as f:
    json.dump(json_str,f)
    print("加载入文件完成...")
1
2
3
(3). loads: 将 字符串 转换为 字典
new_dict = json.loads(json_str)
print(new_dict)
print(type(new_dict))
1
2
3
(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)

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值