KeyError: 0 in Python

KeyError: 0 in Python

我正在尝试获取此 JSON 中返回的第一个对象的 directionstation 的值,但出现以下错误

KeyError: 0

这是我的代码:

print(json.dumps(savedrequest, indent=4))
savedstation = savedrequest[0]['station']
saveddirection = savedrequest[0]['direction']

这是它在打印中返回的内容:

{
     "-bas": {
         "email_address": "dd3@gmail.com", 
         "direction": "Southbound", 
         "station": "place-har"
     }, 
     "-bus": {
         "email_address": "dd4@gmail.com", 
         "direction": "Southbound", 
         "station": "place-su"
     }
 }

我不知道返回时 -bas-bus 是什么,我需要 select 数组中的第一个对象.

您的 JSON 被解码为 "object"(在 python 中称为 dict),它不是数组。因此,它没有特别的 "order"。您认为 "first" 元素实际上可能不是这样存储的。不能保证同一个对象每次都是第一个。

但是,您可以尝试使用 json.loadsobject_pairs_hook 参数(和 json.load). OrderedDict 类似于 dict,但它会记住插入其中的顺序元素。

import json
from collections import OrderedDict

savedrequest = json.loads(data, object_pairs_hook=OrderedDict)

# Then you can get the "first" value as `OrderedDict` remembers order
#firstKey = next(iter(savedrequest))
first = next(iter(savedrequest.values()))

savedstation = first['station']
saveddirection = first['direction']

(此回答感谢 and )