如何在Python中解析JSON文件的不同部分?

时间:2016-09-28 10:52:02

标签: python json parsing python-requests

我正在用Python创建一个程序,从服务器获取总线时间并打印它们。 JSON文件如下所示:

{
"errorcode": "0",
"errormessage": "",
"numberofresults": 4,
"stopid": "175",
"timestamp": "28/09/2016 10:32:44",
"results": [
{
"arrivaldatetime": "28/09/2016 10:43:36",
"duetime": "10",
"departuredatetime": "28/09/2016 10:43:36",
"departureduetime": "10",
"scheduledarrivaldatetime": "28/09/2016 10:44:00",
"scheduleddeparturedatetime": "28/09/2016 10:44:00",
"destination": "Kimmage",
"destinationlocalized": "Camaigh",
"origin": "Harristown",
"originlocalized": "Baile Anraí",
"direction": "Outbound",
"operator": "bac",
"additionalinformation": "",
"lowfloorstatus": "no",
"route": "83",
"sourcetimestamp": "28/09/2016 09:44:49",
"monitored": "true"
},
{
"arrivaldatetime": "28/09/2016 10:43:56",
"duetime": "11",
"departuredatetime": "28/09/2016 10:43:56",
"departureduetime": "11",
"scheduledarrivaldatetime": "28/09/2016 10:14:00",
"scheduleddeparturedatetime": "28/09/2016 10:14:00",
"destination": "Kimmage",
"destinationlocalized": "Camaigh",
"origin": "Harristown",
"originlocalized": "Baile Anraí",
"direction": "Outbound",
"operator": "bac",
"additionalinformation": "",
"lowfloorstatus": "no",
"route": "83",
"sourcetimestamp": "28/09/2016 10:32:40",
"monitored": "true"
},    {
"errorcode": "0",
"errormessage": "",
"numberofresults": 4,
"stopid": "175",
"timestamp": "28/09/2016 10:32:44",
"results": [
{
"arrivaldatetime": "28/09/2016 10:43:36",
"duetime": "10",
"departuredatetime": "28/09/2016 10:43:36",
"departureduetime": "10",
"scheduledarrivaldatetime": "28/09/2016 10:44:00",
"scheduleddeparturedatetime": "28/09/2016 10:44:00",
"destination": "Kimmage",
"destinationlocalized": "Camaigh",
"origin": "Harristown",
"originlocalized": "Baile Anraí",
"direction": "Outbound",
"operator": "bac",
"additionalinformation": "",
"lowfloorstatus": "no",
"route": "83",
"sourcetimestamp": "28/09/2016 09:44:49",
"monitored": "true"
},
{
"arrivaldatetime": "28/09/2016 10:43:56",
"duetime": "11",
"departuredatetime": "28/09/2016 10:43:56",
"departureduetime": "11",
"scheduledarrivaldatetime": "28/09/2016 10:14:00",
"scheduleddeparturedatetime": "28/09/2016 10:14:00",
"destination": "Kimmage",
"destinationlocalized": "Camaigh",
"origin": "Harristown",
"originlocalized": "Baile Anraí",
"direction": "Outbound",
"operator": "bac",
"additionalinformation": "",
"lowfloorstatus": "no",
"route": "83",
"sourcetimestamp": "28/09/2016 10:32:40",
"monitored": "true"
},

使用

返回第一个例如numberofresults没问题
 info = json.load(req)
 print info["numberofresults"]

但是,当我使用duetime尝试相同的操作时,它会返回:

File "bus.py", line 10, in <module>
    print info["route"]
KeyError: 'route'

我认为这是因为JSON文件中不同总线的相同键会多次出现。如何指定我希望Python获取信息的总线?

文件“bus.py”,第10行,in     打印信息['结果'] ['路线'] TypeError:list indices必须是整数,而不是str

编辑:通过使用print info["results"][0]["route"]等管理来使其工作。谢谢大家。

1 个答案:

答案 0 :(得分:0)

print info['results']['routes']

尝试以上。