我有以下json的回应:
{
"routers":[
{
"status":"ACTIVE",
"external_gateway_info":{
"network_id":"4eeac810-19b5-4b9e-82aa-85766506aeec",
"enable_snat":true,
"external_fixed_ips":[
{
"subnet_id":"f5d85de1-dd6d-4b56-8ed4-7a2938f6259a",
"ip_address":"194.168.0.21"
}
]
},
"name":"test_router3",
"admin_state_up":true,
"tenant_id":"f19408f548234b71a5052549cb89ae83",
"distributed":false,
"routes":{
},
"ha":false,
"id":"102fc36a-e2f7-427f-983d-f71b77be0beb"
},
{
"status":"ACTIVE",
"external_gateway_info":{
"network_id":"4eeac810-19b5-4b9e-82aa-85766506aeec",
"enable_snat":true,
"external_fixed_ips":[
{
"subnet_id":"f5d85de1-dd6d-4b56-8ed4-7a2938f6259a",
"ip_address":"194.168.0.20"
}
]
},
"name":"test_router2",
"admin_state_up":true,
"tenant_id":"c3a69d0bbc944b1fbb0873efd71189db",
"distributed":false,
"routes":{
},
"ha":false,
"id":"11b413a3-975e-491c-b0cf-9e2ab11a17c4"
},
{
"status":"ACTIVE",
"external_gateway_info":{
"network_id":"4eeac810-19b5-4b9e-82aa-85766506aeec",
"enable_snat":true,
"external_fixed_ips":[
{
"subnet_id":"f5d85de1-dd6d-4b56-8ed4-7a2938f6259a",
"ip_address":"194.168.0.18"
}
]
},
"name":"test_router0",
"admin_state_up":true,
"tenant_id":"82c3cbe17d8e431a945ee972067b4063",
"distributed":false,
"routes":{
},
"ha":false,
"id":"17ed98c2-36d3-49ed-b9bb-a51616ae0112"
},
{
"status":"ACTIVE",
"external_gateway_info":{
"network_id":"4eeac810-19b5-4b9e-82aa-85766506aeec",
"enable_snat":true,
"external_fixed_ips":[
{
"subnet_id":"f5d85de1-dd6d-4b56-8ed4-7a2938f6259a",
"ip_address":"194.168.0.19"
}
]
},
"name":"test_router1",
"admin_state_up":true,
"tenant_id":"9930b010b96b44c8844dcac7e5b15682",
"distributed":false,
"routes":{
},
"ha":false,
"id":"68135a8f-a28c-43c3-9609-8a23b7b7452e"
},
{
"status":"ACTIVE",
"external_gateway_info":{
"network_id":"4eeac810-19b5-4b9e-82aa-85766506aeec",
"enable_snat":true,
"external_fixed_ips":[
{
"subnet_id":"f5d85de1-dd6d-4b56-8ed4-7a2938f6259a",
"ip_address":"194.168.0.22"
}
]
},
"name":"test_router4",
"admin_state_up":true,
"tenant_id":"f844661b3a7d413a8d66a12e77833539",
"distributed":false,
"routes":{
},
"ha":false,
"id":"6bbb58df-2699-4428-a95e-de51ed4cb37b"
},
{
"status":"ACTIVE",
"external_gateway_info":{
"network_id":"4eeac810-19b5-4b9e-82aa-85766506aeec",
"enable_snat":true,
"external_fixed_ips":[
{
"subnet_id":"f5d85de1-dd6d-4b56-8ed4-7a2938f6259a",
"ip_address":"194.168.0.3"
}
]
},
"name":"external_router1",
"admin_state_up":true,
"tenant_id":"c3a69d0bbc944b1fbb0873efd71189db",
"distributed":false,
"routes":{
},
"ha":false,
"id":"dd7a4123-4b5a-49df-bc42-db71772cffd0"
}
]
}
我需要得到以下内容:
任何人都可以告诉你如何循环json。
我试过循环,但得到错误“整数被视为索引”
答案 0 :(得分:2)
假设您想要json字典的'routers'键中的元素数量:
import json
response = json.reads(response) # Given a json string, returns a python dictionary
return len(response['routers'])
答案 1 :(得分:2)
在这里,您有一个片段,用于计算' id'路线物品属性
>>> import json
>>> json_data = json.loads(raw_json_data)
>>> id_count = sum(1 for route in json_data['routers'] if route.get('id'))
>>>
>>> id_count
6