Python如何操作JSON数据

在Python中处理JSON数据通常涉及以下步骤:
1,导入json模块。

2,使用json.loads()将JSON格式的字符串解析为Python中的数据类型(通常是字典或列表)。

3,使用json.dumps()将Python字典或列表转换回JSON格式的字符串。

4,使用json.load()从文件中加载JSON数据。

5,使用json.dump()将数据写入文件,以JSON格式保存。

示例代码:

import json
 
# 解析JSON字符串到Python数据类型,这里给定字符串,也可以是接口返回
data_str = '{"name": "John", "age": 30, "city": "New York"}'
parsed_data = json.loads(data_str)
print(parsed_data)  # 输出: {'name': 'John', 'age': 30, 'city': 'New York'}


# 将Python数据类型字典转换为JSON字符串
python_dict = {"name": "Jane", "age": 25, "city": "Los Angeles"}
json_str = json.dumps(python_dict)
print(json_str)  # 输出: {"name": "Jane", "age": 25, "city": "Los Angeles"}


# 从物理文件中加载JSON数据,假设当前文件夹有文件名为data.json,
with open('data.json', 'r') as file:
    loaded_data = json.load(file)
    print(loaded_data)


# 将python数据类型python_dict写入文件名为data.json的文件,以JSON格式保存,
with open('data.json', 'w') as file:
    json.dump(python_dict, file)
	
	

欢迎拍砖讨论...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值