python 修改json对象值
时间: 2023-07-26 14:19:33 浏览: 49
要修改 JSON 对象值,可以先将 JSON 字符串解析为 Python 对象,然后修改 Python 对象的属性或元素值,最后将 Python 对象转换回 JSON 字符串。例如,假设有以下 JSON 字符串:
```json
{
"name": "Alice",
"age": 30,
"hobbies": ["reading", "swimming"]
}
```
可以使用 `json` 模块将其解析为 Python 对象:
```python
import json
json_str = '{"name": "Alice", "age": 30, "hobbies": ["reading", "swimming"]}'
data = json.loads(json_str)
```
然后可以修改 Python 对象的属性或元素值:
```python
data['age'] = 31
data['hobbies'].append('running')
```
最后将 Python 对象转换为 JSON 字符串:
```python
new_json_str = json.dumps(data)
print(new_json_str)
```
输出结果为:
```json
{"name": "Alice", "age": 31, "hobbies": ["reading", "swimming", "running"]}
```