【问题标题】:nested loops for json printing用于 json 打印的嵌套循环
【发布时间】:2014-08-09 17:09:10
【问题描述】:

我正在尝试打印这个使用 jason.loads 制作的 python 对象的 LineRef。

{
    "Siri": {
        "ServiceDelivery": {
            "ResponseTimestamp": "2014-08-09T12:07:08.519-04:00",
            "VehicleMonitoringDelivery": [
                {
                    "VehicleActivity": [
                        {
                            "MonitoredVehicleJourney": {
                                "LineRef": "MTA NYCT_B38",
                            }
                        }
                    ]
                }
            ]
        }
    }
}

到目前为止,我已经编写了以下代码:

theJSON = json.loads(data)
for j in theJSON["VehicleMonitoringDelivery"]:
    for i in theJSON["VehicleActivity"]:
        print  [i]["MonitoredVehicleJourney"]["LineRef"]

但它在 JSON 中给出错误

【问题讨论】:

  • “在 JSON 上给出错误”没有提供信息。什么错误?我们不是读心术的人。
  • 如果你使用python 3 print [i]["MonitoredVehicleJourney"]["LineRef"] 将会给你一个错误
  • @PadraicCunningham:它会在 Python 2 中产生同样多的错误。
  • @MartijnPieters,我指的是缺少括号
  • @PadraicCunningham:我知道,我指的是[i] 语法。

标签: python python-3.x json


【解决方案1】:

您不能直接寻址VehicleMonitoringDelivery 键,它嵌套在ServiceDelivery 嵌套在Siri 字典中:

theJSON = json.loads(data)
for delivery in theJSON['Siri']['ServiceDelivery']['VehicleMonitoringDelivery']:
    for activity in delivery['VehicleActivity']:
        print activity['MonitoredVehicleJourney']['LineRef']

或使用索引获取第一个(如果列表为空,可能会失败:

theJSON = json.loads(data)
try:
    delivery = theJSON['Siri']['ServiceDelivery']['VehicleMonitoringDelivery'][0]
    activity = delivery['VehicleActivity'][0]
except IndexError:
    print 'None-such'
else:
    print activity['MonitoredVehicleJourney']['LineRef']

演示:

>>> theJSON = {
...     "Siri": {
...         "ServiceDelivery": {
...             "ResponseTimestamp": "2014-08-09T12:07:08.519-04:00",
...             "VehicleMonitoringDelivery": [
...                 {
...                     "VehicleActivity": [
...                         {
...                             "MonitoredVehicleJourney": {
...                                 "LineRef": "MTA NYCT_B38",
...                             }
...                         }
...                     ]
...                 }
...             ]
...         }
...     }
... }
>>> for delivery in theJSON['Siri']['ServiceDelivery']['VehicleMonitoringDelivery']:
...     for activity in delivery['VehicleActivity']:
...         print activity['MonitoredVehicleJourney']['LineRef']
... 
MTA NYCT_B38

【讨论】:

  • @user3296651:您是否忘记包含theJSON 分配?
  • 当我写 print theJson 然后所有的输出都来了
  • 它现在正在打印,但是结果会多次出现。我只需要打印一次
  • @user3296651:然后在循环中使用break 或使用对列表的索引。
  • 你能帮帮我吗,我是python和json的新手
猜你喜欢
  • 2017-05-29
  • 2023-04-06
  • 2019-02-27
  • 2012-09-14
  • 1970-01-01
  • 1970-01-01
  • 2015-12-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多