Python 试图访问从文件读取的JSON数据结构中的数据

Python 试图访问从文件读取的JSON数据结构中的数据,python,json,python-2.7,Python,Json,Python 2.7,我有以下Python代码来读取JSON文件: import json from pprint import pprint with open('traveladvisory.json') as json_data: print 'json data ',json_data d = json.load(json_data) json_data.close() 下面是用此代码打开的“traveladvisory.json”文件的一部分。变量“d”会打印出所有JSON数据。但

我有以下Python代码来读取JSON文件:

import json
from pprint import pprint
with open('traveladvisory.json') as json_data:
    print 'json data ',json_data
    d = json.load(json_data)
    json_data.close()
下面是用此代码打开的“traveladvisory.json”文件的一部分。变量“d”会打印出所有JSON数据。但我似乎无法获得正确的语法来读取所有的“国家英语”和“咨询文本”字段及其数据并打印出来。有人能帮忙吗?下面是一段json数据(很抱歉,无法很好地打印出来):

{
“元数据”:{
“生成”:{
“时间戳”:1475854624,
“日期”:“2016-10-07 11:37:04”
}
},
“数据”:{
“AF”:{
“国家id”:1000,
“国家iso”:“AF”,
“国家工程”:“阿富汗”,
“国家fra”:“阿富汗”,
“咨询国”:3,
“公布日期”:{
“时间戳”:1473866215,
“日期”:“2016-09-1411:16:55”,
“asp”:“2016-09-14T11:16:55.000000-04:00”
},
"有警告":一,,
“有区域咨询”:0,
"有内容":一,,
“最近更新类型”:“编辑更改”,
“英文”:{
“姓名”:“阿富汗”,
“url slug”:“阿富汗”,
“友好日期”:“2016年9月14日美国东部夏令时11:16”,
“咨询文本”:“避免所有旅行”,
“最近更新”:“健康标签已更新-旅行健康通知(加拿大公共卫生署)。”
},
“fra”:{
“姓名”:“阿富汗”,
“url slug”:“阿富汗”,
“友好日期”:“2016年9月14日11:16”,
“咨询文本”:“\u00c9viter tout seave”,
“最新更新”:“L'onglet Sant\u00e9 a\u00e9t\u00e9 mis\u00e0月-conseils de Sant\u00e9 aux Voyagers(加拿大圣公会机构)。”
}
},
“AL”:{
“国家id”:4000,
“国家iso”:“AL”,
“国家工程”:“阿尔巴尼亚”,
“国家fra”:“Albanie”,
“咨询国”:0,
“公布日期”:{
“时间戳”:1473350931,
“日期”:“2016-09-08 12:08:51”,
“asp”:“2016-09-08T12:08:51.8301256-04:00”
},
“已发出警告”:0,
“有区域咨询”:1,
"有内容":一,,
“最近更新类型”:“编辑更改”,
“英文”:{
“姓名”:“阿尔巴尼亚”,
“url slug”:“阿尔巴尼亚”,
“友好日期”:“2016年9月8日美国东部时间12:08”,
“咨询文本”:“采取正常的安全预防措施(与区域咨询一起)”,
“最近更新”:“进行了编辑更改。”
},
“fra”:{
“姓名”:“阿尔巴尼”,
“url slug”:“albanie”,
“友好日期”:“2016年9月8日12:08”,
“咨询文本”:“s\u00e9curit\u00e9正常值测量值(avec AVERTISSENTS r\u00e9gionaux)”,
“最新更新”:“Un changement mineur a\u00e9t\u00e9 apport\u00e9 au contenu。”
}
},
“DZ”:{
“国家id”:5000,
“国家iso”:“DZ”,
“国家工程”:“阿尔及利亚”,
“国家fra”:“Alg\u00e9rie”,
“咨询国”:1,
“公布日期”:{
“时间戳”:1475593497,
“日期”:“2016-10-04 11:04:57”,
“asp”:“2016-10-04T11:04:57.7727548-04:00”
},
“已发出警告”:0,
“有区域咨询”:1,
"有内容":一,,
“最近更新类型”:“全面TAA审查”,
“英文”:{
“姓名”:“阿尔及利亚”,
“url slug”:“阿尔及利亚”,
“友好日期”:“2016年10月4日美国东部时间11:04”,
“咨询文本”:“高度谨慎(使用区域咨询)”,
“最新更新”:“本旅行建议经过彻底审查和更新。”
},
“fra”:{
“名称”:“Alg\u00e9rie”,
“url slug”:“algerie”,
“友好日期”:“2016年10月4日11:04”,
“咨询文本”:“公平、审慎(avec avertissements r\u00e9gionaux)”,
“最新更新”:“Les pr\u00e9sents Conseils aux voyageurs ont\u00e9t\u00e9 mis\u00e0 jour\u00e0 la suite d\u2019un examen minuteux。”
}
},
}
}
这对我很有用:

for item in d['data']:
    print d['data'][item]['country-eng'], d['data'][item]['eng']['advisory-text']

假设d包含json数据

for country in d["data"]:
    print "Country :",country

    #country.get() gets the value of the key . the second argument is 
    #the value returned in case the key is not present

    print "country-eng : ",country.get("country-eng",0)
    print "advisory-text(eng) :",country["eng"].get("advisory-text",0)
    print "advisory-text(fra) :",country["fra"].get("advisory-text",0)

如果我理解你的问题。以下是如何做到这一点:

import json

with open('traveladvisory.json') as json_data:
    d = json.load(json_data)
#    print(json.dumps(d, indent=4))  # pretty-print data read

for country in d['data']:
    print(country)
    print('  country-eng: {}'.format(d['data'][country]['country-eng']))
    print('  advisory-state: {}'.format(d['data'][country]['advisory-state']))
输出:

DZ
国家:阿尔及利亚
咨询国:1
艾尔
国家:阿尔巴尼亚
咨询国:0
空军
国家:阿富汗
咨询国:3

那么下面的代码适用于python2(如果您需要python3版本,请询问) 您必须使用模块中的功能

#-*- coding: utf-8 -*-
import json                            # import the module we need

with open("traveladvisory.json") as f: # f for file
    d = json.load(f)                   # d is a dictionnary

for key in d['data']:
    print d['data'][key]['country-eng']
    print d['data'][key]['eng']['advisory-text']
处理文件对象时,最好使用with语句。 这样做的好处是,即使在执行过程中引发异常,文件也会在其套件完成后正确关闭

此外,json错误,必须从第98行中删除逗号:

{
   "metadata":{
      "generated":{
         "timestamp":1475854624,
         "date":"2016-10-07 11:37:04"
      }
   },
   "data":{
      "AF":{
         "country-id":1000,
         "country-iso":"AF",
         "country-eng":"Afghanistan",
         "country-fra":"Afghanistan",
         "advisory-state":3,
         "date-published":{
            "timestamp":1473866215,
            "date":"2016-09-14 11:16:55",
            "asp":"2016-09-14T11:16:55.000000-04:00"
         },
         "has-advisory-warning":1,
         "has-regional-advisory":0,
         "has-content":1,
         "recent-updates-type":"Editorial change",
         "eng":{
            "name":"Afghanistan",
            "url-slug":"afghanistan",
            "friendly-date":"September 14, 2016 11:16 EDT",
            "advisory-text":"Avoid all travel",
            "recent-updates":"The Health tab was updated - travel health notices (Public Health Agency of Canada)."
         },
         "fra":{
            "name":"Afghanistan",
            "url-slug":"afghanistan",
            "friendly-date":"14 septembre 2016 11:16 HAE",
            "advisory-text":"\u00c9viter tout voyage",
            "recent-updates":"L'onglet Sant\u00e9 a \u00e9t\u00e9 mis \u00e0 jour - conseils de sant\u00e9 aux voyageurs (Agence de la sant\u00e9 publique du Canada)."
         }
      },
      "AL":{
         "country-id":4000,
         "country-iso":"AL",
         "country-eng":"Albania",
         "country-fra":"Albanie",
         "advisory-state":0,
         "date-published":{
            "timestamp":1473350931,
            "date":"2016-09-08 12:08:51",
            "asp":"2016-09-08T12:08:51.8301256-04:00"
         },
         "has-advisory-warning":0,
         "has-regional-advisory":1,
         "has-content":1,
         "recent-updates-type":"Editorial change",
         "eng":{
            "name":"Albania",
            "url-slug":"albania",
            "friendly-date":"September 8, 2016 12:08 EDT",
            "advisory-text":"Exercise normal security precautions (with regional advisories)",
            "recent-updates":"An editorial change was made."
         },
         "fra":{
            "name":"Albanie",
            "url-slug":"albanie",
            "friendly-date":"8 septembre 2016 12:08 HAE",
            "advisory-text":"Prendre des mesures de s\u00e9curit\u00e9 normales (avec avertissements r\u00e9gionaux)",
            "recent-updates":"Un changement mineur a \u00e9t\u00e9 apport\u00e9 au contenu."
         }
      },
      "DZ":{
         "country-id":5000,
         "country-iso":"DZ",
         "country-eng":"Algeria",
         "country-fra":"Alg\u00e9rie",
         "advisory-state":1,
         "date-published":{
            "timestamp":1475593497,
            "date":"2016-10-04 11:04:57",
            "asp":"2016-10-04T11:04:57.7727548-04:00"
         },
         "has-advisory-warning":0,
         "has-regional-advisory":1,
         "has-content":1,
         "recent-updates-type":"Full TAA review",
         "eng":{
            "name":"Algeria",
            "url-slug":"algeria",
            "friendly-date":"October 4, 2016 11:04 EDT",
            "advisory-text":"Exercise a high degree of caution (with regional advisories)",
            "recent-updates":"This travel advice was thoroughly reviewed and updated."
         },
         "fra":{
            "name":"Alg\u00e9rie",
            "url-slug":"algerie",
            "friendly-date":"4 octobre 2016 11:04 HAE",
            "advisory-text":"Faire preuve d\u2019une grande prudence (avec avertissements r\u00e9gionaux)",
            "recent-updates":"Les pr\u00e9sents Conseils aux voyageurs ont \u00e9t\u00e9 mis \u00e0 jour \u00e0 la suite d\u2019un examen minutieux."
         }
      }

   }
}

你应该在最后一次的第4次去掉逗号。它可能会导致json解码错误无需关闭文件,上下文处理程序
将为您执行此操作