gpt4 book ai didi

php - 如何在 python 中访问深层 JSON 属性

转载 作者:太空宇宙 更新时间:2023-11-03 19:24:18 25 4
gpt4 key购买 nike

此 PHP 代码有效(下面的 json):

$usaData = json_decode(stripslashes(file_get_contents('usaJson.txt')),true);
foreach($usaData['USA']['States'] as $state){
foreach($state['Cities'] as $city){
$zipCode = $city['zipcode'];
}
}
}

我尝试在 python 中做同样的事情,但它给了我 <type 'exceptions.TypeError'>: string indices must be integers

usaData = json.loads(get_file('usaJson.txt'))
for state in usaData['USA']['States']:
for city in state['Cities']:
zipCode = city['zipcode']

我的数据结构是这样的:

{
"USA":{
"States":{
"AL":{
"Cities":[
{
"city":"auburn",
"zipcode":"36830"
},
{
"city":"birmingham",
"zipcode":"35201"
}
]
},
"AK":{
"Cities":[
{
"city":"anchorage",
"zipcode":"99501"
},
{
"city":"fairbanks",
"zipcode":"99701"
}
]
}
}
}
}

那么如何在 python 中访问邮政编码?

最佳答案

你的问题是迭代字典给你的是键,而不是字典中的值。所以你需要的是这样的:

for state_name in usaData['USA']['States']
for city in usaData['USA']['States'][state_name]['Cities']
print city['zipcode']

实在是太丑了

更好的版本是在字典上使用 items 函数,如下所示:

for state_name, state in usaData['USA']['States'].items():
for city in state['Cities']
print city['zipcode']

关于php - 如何在 python 中访问深层 JSON 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8753363/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com