python - 尝试从 JSON 列表打印元素时出现关键错误

标签 python json

我有从 postcodes.io 检索的邮政编码数据 - 我正在开发一些 Python 代码来将此数据读入 JSON 结构。然后,我希望仅打印此结构中的国家和地区项目。

{                                                                                                                                                                                
  "status": 200,                                                                                                                                                                 
  "result": {                                                                                                                                                                    
    "eastings": 536500,                                                                                                                                                          
    "outcode": "SG8",                                                                                                                                                            
    "admin_county": "Hertfordshire",                                                                                                                                             
    "postcode": "SG8 7XU",                                                                                                                                                       
    "incode": "7XU",                                                                                                                                                             
    "codes": {                                                                                                                                                                   
      "parliamentary_constituency": "E14000845",                                                                                                                                 
      "admin_district": "E07000099",                                                                                                                                             
      "parish": "E04004793",                                                                                                                                                     
      "nuts": "UKH23",                                                                                                                                                           
      "admin_county": "E10000015",                                                                                                                                               
      "ccg": "E38000026",                                                                                                                                                        
      "admin_ward": "E05004782"                                                                                                                                                  
    },                                                                                                                                                                           
    "parliamentary_constituency": "North East Hertfordshire",                                                                                                                    
    "quality": 1,                                                                                                                                                                
    "parish": "Royston",                                                                                                                                                         
    "nuts": "Hertfordshire",                                                                                                                                                     
    "european_electoral_region": "Eastern",                                                                                                                                      
    "latitude": 52.0578463413646,                                                                                                                                                
    "msoa": "North Hertfordshire 002",                                                                                                                                           
    "nhs_ha": "East of England",                                                                                                                                                 
    "primary_care_trust": "Hertfordshire",                                                                                                                                       
    "admin_ward": "Royston Meridian",                                                                                                                                            
    "admin_district": "North Hertfordshire",                                                                                                                                     
    "country": "England",                                                                                                                                                        
    "region": "East of England",                                                                                                                                                 
    "longitude": -0.010476012290143,                                                                                                                                             
    "ccg": "NHS Cambridgeshire and Peterborough",                                                                                                                                
    "lsoa": "North Hertfordshire 002D",                                                                                                                                          
    "northings": 241808                                                                                                                                                          
  }                                                                                                                                                                              
} 

这是我的代码:

import sys  
import json
import urllib

def main(argv):
print ("PCinfo Postcode Search")

# Check program invocation is correct
if len(argv) == 2:
    searchterm = argv[1]
else:
    print("Incorrect program call. Usage: PCinfo.py [POSTCODE]")
    sys.exit(0)

url = 'http://api.postcodes.io/postcodes/' 
print ("Calling API with URL " + url + searchterm)

try:
    # For Python 3.0 and later
    from urllib.request import urlopen
    url = url + urllib.parse.quote(searchterm)
    response = urlopen(url).readall().decode('utf-8')
    print("I did 3.0 read")
except ImportError:
    # Fall back to Python 2
    from urllib import urlopen
    url = url + urllib.quote(searchterm)
    response = urlopen(url).read()
    print("I did 2.0 read")

structure = json.loads(response)
print(json.dumps(structure, indent=2))
print(structure["country"])


if __name__== "__main__":
    from sys import argv
    main(argv)

这是程序的输出。第一个打印工作正常并显示整个 JSON 列表,但在尝试仅打印国家/地区时出现“关键错误”?花了好几个小时才看完!请帮忙!

sh-4.4$ python PCinfo7.py SG87XU                                                                                                                                                 
PCinfo Postcode Search                                                                                                                                                           
Calling API with URL http://api.postcodes.io/postcodes/SG87XU                                                                                                                    
I did 2.0 read                                                                                                                                                                   
{                                                                                                                                                                                
  "status": 200,                                                                                                                                                                 
  "result": {                                                                                                                                                                    
    "eastings": 536500,                                                                                                                                                          
    "outcode": "SG8",                                                                                                                                                            
    "admin_county": "Hertfordshire",                                                                                                                                             
    "postcode": "SG8 7XU",                                                                                                                                                       
    "incode": "7XU",                                                                                                                                                             
    "codes": {                                                                                                                                                                   
      "parliamentary_constituency": "E14000845",                                                                                                                                 
      "admin_district": "E07000099",                                                                                                                                             
      "parish": "E04004793",                                                                                                                                                     
      "nuts": "UKH23",                                                                                                                                                           
      "admin_county": "E10000015",                                                                                                                                               
      "ccg": "E38000026",                                                                                                                                                        
      "admin_ward": "E05004782"                                                                                                                                                  
    },                                                                                                                                                                           
    "parliamentary_constituency": "North East Hertfordshire",                                                                                                                    
    "quality": 1,                                                                                                                                                                
    "parish": "Royston",                                                                                                                                                         
    "nuts": "Hertfordshire",                                                                                                                                                     
    "european_electoral_region": "Eastern",                                                                                                                                      
    "latitude": 52.0578463413646,                                                                                                                                                
    "msoa": "North Hertfordshire 002",                                                                                                                                           
    "nhs_ha": "East of England",                                                                                                                                                 
    "primary_care_trust": "Hertfordshire",                                                                                                                                       
    "admin_ward": "Royston Meridian",                                                                                                                                            
    "admin_district": "North Hertfordshire",                                                                                                                                     
    "country": "England",                                                                                                                                                        
    "region": "East of England",                                                                                                                                                 
    "longitude": -0.010476012290143,                                                                                                                                             
    "ccg": "NHS Cambridgeshire and Peterborough",                                                                                                                                
    "lsoa": "North Hertfordshire 002D",                                                                                                                                          
    "northings": 241808                                                                                                                                                          
  }                                                                                                                                                                              
}                                                                                                                                                                                
Traceback (most recent call last):                                                                                                                                               
  File "PCinfo7.py", line 45, in <module>                                                                                                                                        
    main(argv)                                                                                                                                                                   
  File "PCinfo7.py", line 40, in main                                                                                                                                            
    print(structure["country"])   

最佳答案

这是因为 country 不存在于 struct json 中。

结构结果,而结果又包含国家/地区

使用访问它

print(structure['result']['country'])

关于python - 尝试从 JSON 列表打印元素时出现关键错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48528109/

相关文章:

python - SWIG:将 std::map 访问器与 shared_ptr 一起使用?

python - 任何用于读取 Scantron 样式数据的 Python 工具

python - 在 Flask-SQLAlchemy 中,我应该使用 create_all() 在生产环境中创建表吗?

java - 使用 java - ref 的 JSON 模式验证

json - 是否可以像字符串一样将json包装在json字段中?

json - Spring REST 服务、Jersey REST 服务和 Spring+Jersey 解决方案有什么区别?

python - 如何使用 PyWinAuto 单击对话框中的按钮

python - Pyomo:从 Python 代码访问解决方案

java - 使用 jackson 将双向 JPA 实体序列化为 JSON

javascript - 从 AJAX 请求中获取 PHP 中的 JSON 数组