json - KeyError: 0 in Python -
i'm trying values of first object's direction
, station
returned in json, i'm getting following error
keyerror: 0
here's code:
print(json.dumps(savedrequest, indent=4)) savedstation = savedrequest[0]['station'] saveddirection = savedrequest[0]['direction']
and it's returning in print:
{ "-bas": { "email_address": "dd3@gmail.com", "direction": "southbound", "station": "place-har" }, "-bus": { "email_address": "dd4@gmail.com", "direction": "southbound", "station": "place-su" } }
i don't know -bas
or -bus
going when gets returned, need select first object in array.
your json decoded "object" (called dict
in python), it's not array. such, has no particular "order". think "first" element may not stored way. there's no guarantee same object first each time.
what try, however, convert these dict
s ordereddict
s using object_pairs_hook
parameter of json.loads
(and json.load
). ordereddict
dict
, remembers order elements inserted it.
import json collections import ordereddict savedrequest = json.loads(data, object_pairs_hook=ordereddict) # can "first" value `ordereddict` remembers order #firstkey = next(iter(savedrequest)) first = next(iter(savedrequest.values())) savedstation = first['station'] saveddirection = first['direction']
(this answer https://stackoverflow.com/a/6921760 , https://stackoverflow.com/a/21067850)
Comments
Post a Comment