python json的增删改查
时间: 2023-11-11 19:00:06 浏览: 129
Python中操作JSON的增删改查可以通过json模块来实现。
1. 增加:将新的键值对添加到JSON对象中
```python
import json
# 读取JSON文件
with open('data.json', 'r') as f:
data = json.load(f)
# 添加新的键值对
data['new_key'] = 'new_value'
# 写入JSON文件
with open('data.json', 'w') as f:
json.dump(data, f)
```
2. 删除:删除JSON对象中的指定键值对
```python
import json
# 读取JSON文件
with open('data.json', 'r') as f:
data = json.load(f)
# 删除指定键值对
del data['key_to_delete']
# 写入JSON文件
with open('data.json', 'w') as f:
json.dump(data, f)
```
3. 修改:修改JSON对象中的指定键值对
```python
import json
# 读取JSON文件
with open('data.json', 'r') as f:
data = json.load(f)
# 修改指定键值对
data['key_to_modify'] = 'new_value'
# 写入JSON文件
with open('data.json', 'w') as f:
json.dump(data, f)
```
4. 查询:查询JSON对象中的指定键值对
```python
import json
# 读取JSON文件
with open('data.json', 'r') as f:
data = json.load(f)
# 查询指定键值对
value = data.get('key_to_query')
print(value)
```
阅读全文
相关推荐


















