Cant print dissasembled name in Python 2.7

Hi Guys,

So I am trying to print the bus numbers in python. However when i go to access the dissabsembled name key it comes back with this error:

Traceback (most recent call last):
  File "C:\Python27\curl test v2.0.py", line 13, in <module>
    print(JSONData['stopEvents']['disassembledName'])
TypeError: list indices must be integers, not str

any help would be appreciated here is my code:

 import requests, json
import os
url = 'https://api.transport.nsw.gov.au/v1/tp/departure_mon?outputFormat=rapidJSON&coordOutputFormat=EPSG%3A4326&mode=direct&type_dm=stop&name_dm=10137620&itdDate=20180110&itdTime=1235&departureMonitorMacro=true&TfNSWDM=true&version=10.2.1.42'
payload = ''

headers = {'content-type': 'application/json', 'Accept-Charset': 'UTF-8', 'Authorization': 'apikey ' }
r = requests.get(url, data=payload, headers=headers)
print(r)


JSONData = json.loads(r.content)

print(JSONData['stopEvents']['disassembledName'])

Hey,

Firstly when asking for help online you might want to remove your API key from your code - it’s not safe to be spreading it about :slight_smile:

Secondly, one of your problems is that stopEvents is a list, not an object. A list contains multiple objects, which means you need to select an object with an integer (number) like: JSONData['stopEvents'][0] (0 will get you the first item).

Thirdly, there are multiple disassembledNames, for different sections. I assume you want the parent’s disassembled name, which you can get like this:
print(JSONData['stopEvents'][0]['location']['parent']['disassembledName'])

If you want to see the disassembledName for each of the objects in the stopEvents, then iterate over stopEvents and replace the 0 with the number of the object you want.

[quote=“Lockie, post:2, topic:1134”]

Thank you very much big help!

1 Like