python json多层嵌套取值,使用Python从嵌套JSON对象中提取数据
时间: 2024-02-27 08:57:34 浏览: 612
可以使用Python内置的json模块来处理JSON数据。如果JSON数据是多层嵌套的,可以使用递归或循环来获取需要的值。
以下是一个示例JSON对象:
```
{
"name": "John",
"age": 30,
"address": {
"city": "New York",
"state": "NY",
"zip": "10001"
},
"phone_numbers": [
{
"type": "home",
"number": "555-1234"
},
{
"type": "work",
"number": "555-5678"
}
]
}
```
如果要获取"name"的值,可以使用以下代码:
```python
import json
json_str = '{"name": "John", "age": 30}'
json_data = json.loads(json_str)
name = json_data['name']
```
如果要获取"city"的值,可以使用以下代码:
```python
import json
json_str = '{"name": "John", "age": 30, "address": {"city": "New York", "state": "NY", "zip": "10001"}}'
json_data = json.loads(json_str)
city = json_data['address']['city']
```
如果要获取"home"的电话号码,可以使用以下代码:
```python
import json
json_str = '{"name": "John", "age": 30, "phone_numbers": [{"type": "home", "number": "555-1234"}, {"type": "work", "number": "555-5678"}]}'
json_data = json.loads(json_str)
for phone_number in json_data['phone_numbers']:
if phone_number['type'] == 'home':
home_phone_number = phone_number['number']
break
```
以上是几个示例,根据需要可以进行适当修改。
阅读全文