python json添加建值和读取键值
时间: 2024-03-01 12:46:15 浏览: 270
python读取json文件方法说明
以下是Python中添加JSON键值和读取JSON键值的示例代码:
1. 添加JSON键值
```python
import json
# 创建一个空的JSON对象
data = {}
# 添加键值对
data['name'] = 'John'
data['age'] = 30
data['city'] = 'New York'
# 将JSON对象转换为JSON字符串
json_data = json.dumps(data)
# 打印JSON字符串
print(json_data)
```
输出结果为:
```
{"name": "John", "age": 30, "city": "New York"}
```
2. 读取JSON键值
```python
import json
# JSON字符串
json_data = '{"name": "John", "age": 30, "city": "New York"}'
# 将JSON字符串转换为JSON对象
data = json.loads(json_data)
# 读取键值
name = data['name']
age = data['age']
city = data['city']
# 打印键值
print(name)
print(age)
print(city)
```
输出结果为:
```
John
30
New York
```
阅读全文