python 根据key去value json
时间: 2023-11-27 22:03:27 浏览: 165
可以使用Python内置的`json`模块来解析JSON数据,并根据 key 值获取对应的 value。示例代码如下:
```python
import json
# JSON 数据
data = '{"name": "John", "age": 30, "city": "New York"}'
# 将JSON数据解析为Python对象
obj = json.loads(data)
# 根据 key 值获取对应的 value
print(obj["name"]) # 输出:John
print(obj["age"]) # 输出:30
print(obj["city"]) # 输出:New York
```
如果JSON数据很大,可以使用`json.load()`函数从文件中加载JSON数据。例如:
```python
import json
# 从文件中加载JSON数据
with open('data.json', 'r') as f:
data = json.load(f)
# 根据 key 值获取对应的 value
print(data["name"])
```
其中,`data.json`是包含JSON数据的文件名。
相关问题
python获取json key value戴安
可以使用Python内置的`json`模块来处理JSON数据。以下是一个简单的示例代码,可以获取JSON中的键和值:
```python
import json
# 一个JSON字符串
json_str = '{"name": "David", "age": 30, "city": "Beijing"}'
# 将JSON字符串解析为Python对象
json_obj = json.loads(json_str)
# 遍历Python对象,获取键和值
for key, value in json_obj.items():
print(key, value)
```
输出结果为:
```
name David
age 30
city Beijing
```
以上代码中,`json.loads()`函数将JSON字符串解析为Python对象,`json_obj.items()`方法获取键值对,再使用`for`循环遍历输出键和值。
python 读取json 从value取key
可以使用 Python 的内置 json 库来读取 JSON 格式的数据。假设你有一个 JSON 文件 `data.json`,里面包含下面这样的数据:
```json
{
"name": "Alice",
"age": 25,
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "CA",
"zip": "12345"
}
}
```
你可以使用以下代码来读取 `data.json` 并从中提取出 `address` 的各个字段:
```python
import json
# 读取 JSON 文件
with open('data.json', 'r') as f:
data = json.load(f)
# 提取 address 的各个字段
street = data['address']['street']
city = data['address']['city']
state = data['address']['state']
zip_code = data['address']['zip']
# 输出结果
print("Street:", street)
print("City:", city)
print("State:", state)
print("Zip code:", zip_code)
```
输出结果为:
```
Street: 123 Main St
City: Anytown
State: CA
Zip code: 12345
```
这里使用了 `json.load()` 方法将 JSON 文件中的数据读取为 Python 字典,然后从字典中提取出需要的字段。
阅读全文
相关推荐















