繁体   English   中英

获取 AttributeError: 'str' 对象在遍历 json 文件时没有属性 'get'

[英]Getting AttributeError: 'str' object has no attribute 'get' when traversing through json file

当我尝试从 python 中的 json 文件获取值时出现此错误。 我知道这是一个非常简单的错误,我无法弄清楚。 这是我的代码:

json 响应

{'responseCode': 0, 'responseDesc': {'booking_date_utc': None, 'city_id': 6, 'city_name': 'Hyderabad', 'start_date': None, 'trip_id': 1, 'trip_name': 'custom-trip-name', 'user_id': 1}}
if res['responseCode'] == 0:
    for i in res['responseDesc']:
        city_info = 'Your Booking Details:\n Booking Date: {},\n City Name: {},\n Travel Date:{},\n Trip Name: {}'.format(i.get('booking_date_utc'), i.get('city_name'), i.get('start_date'), i.get('trip_name'))
        print(city_info)

任何帮助,将不胜感激。 提前致谢

当您像这样迭代字典时,迭代器i实际上代表键。 请参阅下面的示例代码:

res = {'responseCode': 0,
       'responseDesc': {'booking_date_utc': None, 'city_id': 6, 'city_name': 'Hyderabad', 'start_date': None,
                        'trip_id': 1, 'trip_name': 'custom-trip-name', 'user_id': 1}}
if res['responseCode'] == 0:
    for i in res['responseDesc']:
        print(i)
# Output:
booking_date_utc
city_id
city_name
start_date
trip_id
trip_name
user_id

此外,您的 res 对象实际上是一个字典而不是一个 json。 虽然python字典看起来很像json,但它们是不同的东西。 您可以将其识别为字典,由于None值,json 不知道 None,但使用null表示空值。

所以回到你的问题:当试图调用 i.get("booking_date_utc") 时,你实际上尝试这样做: "booking_date_utc".get("booking_date_utc") ,因为i已经是关键。

最后,您想要做的是删除循环并只访问键,就像评论中已经建议的那样。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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