简体   繁体   中英

return value in json file 5 levels deep in python using simplejson

Trying to get values from a JSON file, up to 5 levels deep in python. Currently getting this error;

Traceback (most recent call last):
File "traffic.py", line 9, in <module>
print data['features'][0]['properties']['location']['road']
KeyError: 'location'

Here is my code so far;

import urllib, simplejson
url = "http://131940.qld.gov.au/api/json/v1/events/?state=qld"
response = urllib.urlopen(url);
data = simplejson.loads(response.read())

for data['features'][0]['properties'] in data['features']:
    print data['features'][0]['properties']['location']['road']

Snippet of the JSON file;

{
  "type": "FeatureCollection",
  "published": "27/06/2015 19:15",
  "rights": {
    "owner": "Department of Transport and Main Roads",
    "disclaimer": "The State of Queensland makes no statements, representations or warranties about the accuracy, currency, reliability or completeness of the information contained in this feed.",
    "copyright": "Copyright in material within this feed is owned by the State of Queensland or other entities which provide material for the website by arrangement. Please consult the 131940 website for further information."
  },
  "features": [
    {
      "type": "Feature",
      "id": 55141891,
      "source": {
        "externalid": null,
        "id": 2,
        "name": "Department of Transport and Main Roads"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [
          152.356430053711,
          -27.5912036895752
        ],
        "classifier": null
      },
      "properties": {
        "location": {
          "road": "VICTORIA STREET",
          "suburb": "FOREST HILL",
          "localGovernment": null,
          "postcode": "4342",
          "region": {
            "id": 104,
            "name": "Darling Downs"
          },
          "state": "QLD",
          "direction": "Both Directions",
          "additional": "Gallipoli Rememberence March.\r\nVictoria Street Forest Hill, between Church Street and William Steet"
        },
        "event": {
          "isHighImpact": false,
          "description": "Special Event Both Directions\r\nGallipoli Rememberence March.\r\nVictoria Street Forest Hill, between Church Street and William Steet.\r\nCommencing: 22 August 2015, between the hours of 10:30am and 11:15am\r\nConcluding: 22 August 2015.\r\nRoad closed both directions\r\nNo delays expected. Use alternative route. \r\n\r\n\r\nLast edited: 08 May 2015 09:35",
          "type": "Planned",
          "cause": "Special Event",
          "incidentType": "",
          "incidentDetails": "N/A",
          "delay": "No delays expected",
          "advice": "Use alternative route",
          "limit": null,
          "extraDetails": "\r\n",
          "impact": null
        },
        "temporal": {
          "start": "22/08/2015T10:30:00",
          "modified": "08/05/2015T09:35:14",
          "end": null,
          "review": null,
          "lastReviewed": null,
          "nextUpdate": null
        },
        "metadata": {
          "status": null,
          "owner": null,
          "modifiedBy": null,
          "url": "http://131940.qld.gov.au/road-conditions.aspx?id=55141891",
          "contactEmail": null
        }
      }
    },

I have tried multiple combinations of print data['features'][0]['properties']['location']['road'] eg. trying different variations of indexes or tag names after ['properties'] with no success.

Any advice/code example on how to read that far into the JSON file, and an explanation of how the dictionary/list is structured would be greatly appreciated.

You should change your for loop to:

for info in data['features']:
    print info['properties']['location']['road']

Explanation: data['features'] returns a list of dictionaries where each one is as follows:

{u'geometry': {u'type': u'Point', u'classifier': None, u'coordinates': [152.356430053711, -27.5912036895752]}, u'source': {u'externalid': None, u'id': 2, u'name': u'Department of Transport and Main Roads'}, u'type': u'Feature', u'id': 55141891, u'properties': {u'temporal': {u'end': None, u'nextUpdate': None, u'lastReviewed': None, u'modified': u'08/05/2015T09:35:14', u'start': u'22/08/2015T10:30:00', u'review': None}, u'metadata': {u'status': None, u'owner': None, u'contactEmail': None, u'modifiedBy': None, u'url': u'http://131940.qld.gov.au/road-conditions.aspx?id=55141891'}, u'location': {u'direction': u'Both Directions', u'additional': u'Gallipoli Rememberence March.\r\nVictoria Street Forest Hill, between Church Street and William Steet', u'region': {u'id': 104, u'name': u'Darling Downs'}, u'localGovernment': None, u'suburb': u'FOREST HILL', u'state': u'QLD', u'postcode': u'4342', u'road': u'VICTORIA STREET'}, u'event': {u'impact': None, u'description': u'Special Event Both Directions\r\nGallipoli Rememberence March.\r\nVictoria Street Forest Hill, between Church Street and William Steet.\r\nCommencing: 22 August 2015, between the hours of 10:30am and 11:15am\r\nConcluding: 22 August 2015.\r\nRoad closed both directions\r\nNo delays expected. Use alternative route. \r\n\r\n\r\nLast edited: 08 May 2015 09:35', u'type': u'Planned', u'advice': u'Use alternative route', u'delay': u'No delays expected', u'incidentDetails': u'N/A', u'limit': None, u'incidentType': u'', u'extraDetails': u'\r\n', u'cause': u'Special Event', u'isHighImpact': False}}}

so all we need to do now is get to ['properties']['location']['road'] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM