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

时间:2017-03-20 10:07:05

标签: 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数据。但我似乎无法正确阅读所有“乡村英语”的语法。和'咨询文本'字段及其数据并打印出来。有人可以帮忙吗?这是json数据的一部分(对不起,不能打印出来):

{
   "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 个答案:

答案 0 :(得分:0)

这对我有用:

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

答案 1 :(得分:0)

假设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)

答案 2 :(得分: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
  country-eng: Algeria
  advisory-state: 1
AL
  country-eng: Albania
  advisory-state: 0
AF
  country-eng: Afghanistan
  advisory-state: 3

答案 3 :(得分:0)

然后代码下面的python2工作(如果你需要python3版本请问) 您必须使用load 模块

中的json功能
#-*- 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."
         }
      }

   }
}