迭代python

时间:2017-03-17 08:37:15

标签: python json

我正在迭代这样一个Feed:

{"siri":{"serviceDelivery":{"responseTimestamp":"2017-03-14T18:37:23Z","producerRef":"IVTR_RELAIS","status":"true","estimatedTimetableDelivery":[
{"lineRef":{"value":"C01742"},"directionRef":{"value":""},"datedVehicleJourneyRef":{"value":"SNCF-ACCES:VehicleJourney::UPAL97_20170314:LOC"},"vehicleMode":["RAIL"],"routeRef":{},"publishedLineName":[{"value":"RER A"}],"directionName":[],"originRef":{},"originName":[],"originShortName":[],"destinationDisplayAtOrigin":[],"via":[],"destinationRef":{"value":"STIF:StopPoint:Q:40918:"},"destinationName":[{"value":"GARE DE CERGY LE HAUT"}],"destinationShortName":[],"originDisplayAtDestination":[],"operatorRef":{"value":"SNCF-ACCES:Operator::SNCF:"},"productCategoryRef":{},"vehicleJourneyName":[],"journeyNote":[],"firstOrLastJourney":"UNSPECIFIED","additionalVehicleJourneyRef":[],"estimatedCalls":{"estimatedCall":[{"stopPointRef":{"value":"STIF:StopPoint:Q:411321:"},"expectedArrivalTime":"2017-03-14T20:02:00.000Z","expectedDepartureTime":"2017-03-14T20:02:00.000Z","aimedArrivalTime":"2017-03-14T20:02:00.000Z","aimedDepartureTime":"2017-03-14T20:02:00.000Z","stopPointName":[],"originDisplay":[],"destinationDisplay":[],"arrivalOperatorRefs":[]},{"stopPointRef":{"value":"STIF:StopPoint:Q:411368:"},"expectedArrivalTime":"2017-03-14T20:09:00.000Z","expectedDepartureTime":"2017-03-14T20:09:00.000Z","aimedArrivalTime":"2017-03-14T20:09:00.000Z","aimedDepartureTime":"2017-03-14T20:09:00.000Z","stopPointName":[],"originDisplay":[],"destinationDisplay":[],"arrivalOperatorRefs":[]},{"stopPointRef":{"value":"STIF:StopPoint:Q:411352:"},"expectedArrivalTime":"2017-03-14T20:05:00.000Z","expectedDepartureTime":"2017-03-14T20:05:00.000Z","aimedArrivalTime":"2017-03-14T20:05:00.000Z","aimedDepartureTime":"2017-03-14T20:05:00.000Z","stopPointName":[],"originDisplay":[],"destinationDisplay":[],"arrivalOperatorRefs":[]},{"stopPointRef":{"value":"STIF:StopPoint:Q:41528:"},"expectedArrivalTime":"2017-03-14T19:56:00.000Z","expectedDepartureTime":"2017-03-14T19:56:00.000Z","aimedArrivalTime":"2017-03-14T19:56:00.000Z","aimedDepartureTime":"2017-03-14T19:56:00.000Z","stopPointName":[],"originDisplay":[],"destinationDisplay":[],"arrivalOperatorRefs":[]},{"stopPointRef":{"value":"STIF:StopPoint:Q:40918:"},"expectedArrivalTime":"2017-03-14T20:12:00.000Z","aimedArrivalTime":"2017-03-14T20:12:00.000Z","aimedDepartureTime":"2017-03-14T20:12:00.000Z","stopPointName":[],"originDisplay":[],"destinationDisplay":[],"arrivalOperatorRefs":[]}]},"recordedAtTime":"2017-03-14T18:37:12.314Z"}
,{"lineRef":{"value":"C00049"},"directionRef":{"value":""},"datedVehicleJourneyRef":{"value":"004_DEVILLAIRS:VehicleJourney::109173051020957:LOC"},"vehicleMode":[],"routeRef":{},"publishedLineName":[{"value":"42"}],"directionName":[{"value":"Aller"}],"originRef":{},"originName":[],"originShortName":[],"destinationDisplayAtOrigin":[],"via":[],"destinationRef":{"value":"STIF:StopPoint:BP:12689:"},"destinationName":[{"value":"L'Onde Maison des Arts"}],"destinationShortName":[],"originDisplayAtDestination":[],"operatorRef":{"value":"004_DEVILLAIRS:Operator::004_DEVILLAIRS_Operator__004_DEVILLAIRS_Company__Devillairs 4_LOC_:"},"productCategoryRef":{},"vehicleJourneyName":[],"journeyNote":[],"firstOrLastJourney":"UNSPECIFIED","additionalVehicleJourneyRef":[],"estimatedCalls":{"estimatedCall":[{"stopPointRef":{"value":"STIF:StopPoint:Q:12690:"},"expectedArrivalTime":"2017-03-14T18:44:26.000Z","expectedDepartureTime":"2017-03-14T18:44:26.000Z","aimedArrivalTime":"2017-03-14T18:43:39.000Z","aimedDepartureTime":"2017-03-14T18:43:39.000Z","stopPointName":[],"originDisplay":[],"destinationDisplay":[],"arrivalOperatorRefs":[]},{"stopPointRef":{"value":"STIF:StopPoint:Q:12684:"},"expectedArrivalTime":"2017-03-14T18:38:51.000Z","expectedDepartureTime":"2017-03-14T18:38:51.000Z","aimedArrivalTime":"2017-03-14T18:34:51.000Z","aimedDepartureTime":"2017-03-14T18:34:51.000Z","stopPointName":[],"originDisplay":[],"destinationDisplay":[],"arrivalOperatorRefs":[]},{"stopPointRef":{"value":"STIF:StopPoint:Q:40538:"},"expectedArrivalTime":"2017-03-14T18:40:53.000Z","expectedDepartureTime":"2017-03-14T18:40:53.000Z","aimedArrivalTime":"2017-03-14T18:37:24.000Z","aimedDepartureTime":"2017-03-14T18:37:24.000Z","stopPointName":[],"originDisplay":[],"destinationDisplay":[],"arrivalOperatorRefs":[]},{"stopPointRef":{"value":"STIF:StopPoint:Q:12678:"},"expectedArrivalTime":"2017-03-14T18:41:10.000Z","expectedDepartureTime":"2017-03-14T18:41:10.000Z","aimedArrivalTime":"2017-03-14T18:37:57.000Z","aimedDepartureTime":"2017-03-14T18:37:57.000Z","stopPointName":[],"originDisplay":[],"destinationDisplay":[],"arrivalOperatorRefs":[]},{"stopPointRef":{"value":"STIF:StopPoint:Q:12682:"},"expectedArrivalTime":"2017-03-14T18:40:00.000Z","expectedDepartureTime":"2017-03-14T18:40:00.000Z","aimedArrivalTime":"2017-03-14T18:36:21.000Z","aimedDepartureTime":"2017-03-14T18:36:21.000Z","stopPointName":[],"originDisplay":[],"destinationDisplay":[],"arrivalOperatorRefs":[]},{"stopPointRef":{"value":"STIF:StopPoint:Q:41690:"},"expectedArrivalTime":"2017-03-14T18:42:17.000Z","expectedDepartureTime":"2017-03-14T18:42:17.000Z","aimedArrivalTime":"2017-03-14T18:39:00.000Z","aimedDepartureTime":"2017-03-14T18:39:00.000Z","stopPointName":[],"originDisplay":[],"destinationDisplay":[],"arrivalOperatorRefs":[]},{"stopPointRef":{"value":"STIF:StopPoint:Q:12743:"},"expectedDepartureTime":"2017-03-14T18:15:00.000Z","aimedDepartureTime":"2017-03-14T18:15:00.000Z","stopPointName":[],"originDisplay":[],"destinationDisplay":[],"arrivalOperatorRefs":[]},{"stopPointRef":{"value":"STIF:StopPoint:Q:12680:"},"expectedArrivalTime":"2017-03-14T18:40:24.000Z","expectedDepartureTime":"2017-03-14T18:40:24.000Z","aimedArrivalTime":"2017-03-14T18:36:52.000Z","aimedDepartureTime":"2017-03-14T18:36:52.000Z","stopPointName":[],"originDisplay":[],"destinationDisplay":[],"arrivalOperatorRefs":[]},{"stopPointRef":{"value":"STIF:StopPoint:Q:12676:"},"expectedArrivalTime":"2017-03-14T18:41:42.000Z","expectedDepartureTime":"2017-03-14T18:41:42.000Z","aimedArrivalTime":"2017-03-14T18:38:29.000Z","aimedDepartureTime":"2017-03-14T18:38:29.000Z","stopPointName":[],"originDisplay":[],"destinationDisplay":[],"arrivalOperatorRefs":[]}]},"recordedAtTime":"2017-03-14T18:35:51.000Z"}
,{"lineRef":{"value":"C01375"},"directionRef":{"value":""},"datedVehicleJourneyRef":{"value":"RATP:VehicleJourney::M5.R.1937.1:LOC"},"vehicleMode":[],"routeRef":{},"publishedLineName":[{"value":"Place d'Italie / Bobigny Pablo Picasso"}],"directionName":[{"value":"Bobigny Pablo Picasso"}],"originRef":{},"originName":[],"originShortName":[],"destinationDisplayAtOrigin":[],"via":[],"destinationRef":{"value":"STIF:StopPoint:Q:22015:"},"destinationName":[{"value":"Bobigny Pablo Picasso"}],"destinationShortName":[],"originDisplayAtDestination":[],"operatorRef":{},"productCategoryRef":{},"vehicleJourneyName":[],"journeyNote":[],"firstOrLastJourney":"UNSPECIFIED","additionalVehicleJourneyRef":[],"estimatedCalls":{"estimatedCall":[{"stopPointRef":{"value":"STIF:StopPoint:Q:22003:"},"expectedDepartureTime":"2017-03-14T18:37:00.000Z","stopPointName":[],"originDisplay":[],"destinationDisplay":[],"arrivalOperatorRefs":[]},{"stopPointRef":{"value":"STIF:StopPoint:Q:22008:"},"expectedDepartureTime":"2017-03-14T18:37:00.000Z","stopPointName":[],"originDisplay":[],"destinationDisplay":[],"arrivalOperatorRefs":[]},{"stopPointRef":{"value":"STIF:StopPoint:Q:22017:"},"expectedDepartureTime":"2017-03-14T18:37:00.000Z","stopPointName":[],"originDisplay":[],"destinationDisplay":[],"arrivalOperatorRefs":[]},{"stopPointRef":{"value":"STIF:StopPoint:Q:21952:"},"expectedDepartureTime":"2017-03-14T18:37:00.000Z","stopPointName":[],"originDisplay":[],"destinationDisplay":[],"arrivalOperatorRefs":[]},{"stopPointRef":{"value":"STIF:StopPoint:Q:22009:"},"expectedDepartureTime":"2017-03-14T18:37:00.000Z","stopPointName":[],"originDisplay":[],"destinationDisplay":[],"arrivalOperatorRefs":[]},{"stopPointRef":{"value":"STIF:StopPoint:Q:22016:"},"expectedDepartureTime":"2017-03-14T18:37:00.000Z","stopPointName":[],"originDisplay":[],"destinationDisplay":[],"arrivalOperatorRefs":[]},{"stopPointRef":{"value":"STIF:StopPoint:Q:22007:"},"expectedDepartureTime":"2017-03-14T18:37:00.000Z","stopPointName":[],"originDisplay":[],"destinationDisplay":[],"arrivalOperatorRefs":[]},{"stopPointRef":{"value":"STIF:StopPoint:Q:21903:"},"expectedDepartureTime":"2017-03-14T18:37:00.000Z","stopPointName":[],"originDisplay":[],"destinationDisplay":[],"arrivalOperatorRefs":[]},{"stopPointRef":{"value":"STIF:StopPoint:Q:22005:"},"expectedDepartureTime":"2017-03-14T18:37:00.000Z","stopPointName":[],"originDisplay":[],"destinationDisplay":[],"arrivalOperatorRefs":[]},{"stopPointRef":{"value":"STIF:StopPoint:Q:22006:"},"expectedDepartureTime":"2017-03-14T18:37:00.000Z","stopPointName":[],"originDisplay":[],"destinationDisplay":[],"arrivalOperatorRefs":[]},{"stopPointRef":{"value":"STIF:StopPoint:Q:22004:"},"expectedDepartureTime":"2017-03-14T18:37:00.000Z","stopPointName":[],"originDisplay":[],"destinationDisplay":[],"arrivalOperatorRefs":[]},{"stopPointRef":{"value":"STIF:StopPoint:Q:22012:"},"expectedDepartureTime":"2017-03-14T18:37:00.000Z","stopPointName":[],"originDisplay":[],"destinationDisplay":[],"arrivalOperatorRefs":[]},{"stopPointRef":{"value":"STIF:StopPoint:Q:22011:"},"expectedDepartureTime":"2017-03-14T18:37:00.000Z","stopPointName":[],"originDisplay":[],"destinationDisplay":[],"arrivalOperatorRefs":[]},{"stopPointRef":{"value":"STIF:StopPoint:Q:22013:"},"expectedDepartureTime":"2017-03-14T18:37:00.000Z","stopPointName":[],"originDisplay":[],"destinationDisplay":[],"arrivalOperatorRefs":[]},{"stopPointRef":{"value":"STIF:StopPoint:Q:21981:"},"expectedDepartureTime":"2017-03-14T18:37:00.000Z","stopPointName":[],"originDisplay":[],"destinationDisplay":[],"arrivalOperatorRefs":[]},{"stopPointRef":{"value":"STIF:StopPoint:Q:22000:"},"expectedDepartureTime":"2017-03-14T18:37:00.000Z","stopPointName":[],"originDisplay":[],"destinationDisplay":[],"arrivalOperatorRefs":[]},{"stopPointRef":{"value":"STIF:StopPoint:Q:22010:"},"expectedDepartureTime":"2017-03-14T18:37:00.000Z","stopPointName":[],"originDisplay":[],"destinationDisplay":[],"arrivalOperatorRefs":[]},{"stopPointRef":{"value":"STIF:StopPoint:Q:22002:"},"expectedDepartureTime":"2017-03-14T18:37:00.000Z","stopPointName":[],"originDisplay":[],"destinationDisplay":[],"arrivalOperatorRefs":[]},{"stopPointRef":{"value":"STIF:StopPoint:Q:22001:"},"expectedDepartureTime":"2017-03-14T18:37:00.000Z","stopPointName":[],"originDisplay":[],"destinationDisplay":[],"arrivalOperatorRefs":[]}]},"recordedAtTime":"2017-03-14T18:36:55.890Z"}
,{"lineRef":{"value":"C00774"},"directionRef":{"value":""},"datedVehicleJourneyRef":{"value":"STIVO:VehicleJourney::268437511:LOC"},"vehicleMode":[],"routeRef":{},"publishedLineName":[{"value":"CERGY PREFECTURE-VAUREAL TOUPETS"}],"directionName":[{"value":"R"}],"originRef":{},"originName":[],"originShortName":[],"destinationDisplayAtOrigin":[],"via":[],"destinationRef":{"value":"STIF:StopPoint:Q:10118:"},"destinationName":[{"value":"Préfecture RER"}],"destinationShortName":[],"originDisplayAtDestination":[],"operatorRef":{},"productCategoryRef":{},"vehicleJourneyName":[],"journeyNote":[],"firstOrLastJourney":"UNSPECIFIED","additionalVehicleJourneyRef":[],"estimatedCalls":{"estimatedCall":[{"stopPointRef":{"value":"STIF:StopPoint:Q:8729:"},"expectedDepartureTime":"2017-03-14T18:39:31.000Z","aimedDepartureTime":"2017-03-14T18:39:00.000Z","stopPointName":[],"originDisplay":[],"destinationDisplay":[],"arrivalOperatorRefs":[]},{"stopPointRef":{"value":"STIF:StopPoint:Q:8731:"},"expectedDepartureTime":"2017-03-14T18:40:31.000Z","aimedDepartureTime":"2017-03-14T18:40:20.000Z","stopPointName":[],"originDisplay":[],"destinationDisplay":[],"arrivalOperatorRefs":[]},{"stopPointRef":{"value":"STIF:StopPoint:Q:8730:"},"expectedDepartureTime":"2017-03-14T18:40:46.000Z","aimedDepartureTime":"2017-03-14T18:39:51.000Z","stopPointName":[],"originDisplay":[],"destinationDisplay":[],"arrivalOperatorRefs":[]}]},"recordedAtTime":"2017-03-14T18:36:43.000Z"}
,{"lineRef":{"value":"C00697"},"directionRef":{"value":""},"datedVehicleJourneyRef":{"value":"SRVSAE:VehicleJourney::34661-1:LOC"},"vehicleMode":["BUS"],"routeRef":{},"publishedLineName":[{"value":"H   "}],"directionName":[],"originRef":{"value":"STIF:StopPoint:BP:20399:"},"originName":[{"value":"Versailles Rive Gauche"}],"originShortName":[],"destinationDisplayAtOrigin":[],"via":[],"destinationRef":{"value":"STIF:StopPoint:BP:4122:"},"destinationName":[{"value":"La Celle St Cloud - Gare"}],"destinationShortName":[],"originDisplayAtDestination":[],"operatorRef":{"value":"SRVSAE:Operator::56 :"},"productCategoryRef":{},"vehicleJourneyName":[{"value":"34661-1"}],"journeyNote":[],"firstOrLastJourney":"OTHER_SERVICE","additionalVehicleJourneyRef":[],"estimatedCalls":{"estimatedCall":[{"stopPointRef":{"value":"STIF:StopPoint:Q:4062:"},"expectedArrivalTime":"2017-03-14T18:39:55.000Z","expectedDepartureTime":"2017-03-14T18:39:55.000Z","aimedArrivalTime":"2017-03-14T18:35:00.000Z","aimedDepartureTime":"2017-03-14T18:35:00.000Z","stopPointName":[],"originDisplay":[],"destinationDisplay":[],"arrivalOperatorRefs":[]},{"stopPointRef":{"value":"STIF:StopPoint:Q:4064:"},"expectedArrivalTime":"2017-03-14T18:38:58.000Z","expectedDepartureTime":"2017-03-14T18:38:58.000Z","aimedArrivalTime":"2017-03-14T18:34:10.000Z","aimedDepartureTime":"2017-03-14T18:34:10.000Z","stopPointName":[],"originDisplay":[],"destinationDisplay":[],"arrivalOperatorRefs":[]},{"stopPointRef":{"value":"STIF:StopPoint:Q:4068:"},"expectedArrivalTime":"2017-03-14T18:36:48.000Z","expectedDepartureTime":"2017-03-14T18:36:48.000Z","aimedArrivalTime":"2017-03-14T18:32:00.000Z","aimedDepartureTime":"2017-03-14T18:32:00.000Z","stopPointName":[],"originDisplay":[],"destinationDisplay":[],"arrivalOperatorRefs":[]}]},"recordedAtTime":"2017-03-14T18:33:37.000Z"}
]}}}

使用python脚本:

import datetime
import time

import dateutil.parser
import pytz
import json
import gtfs_realtime_pb2
from traceback import print_exc

EPOCH = datetime.datetime(1970, 1, 1, tzinfo=pytz.utc)

def handle_siri(raw):
    siri_data = json.loads(raw.decode('utf-8'))['siri']
    msg = gtfs_realtime_pb2.FeedMessage()
    msg.header.gtfs_realtime_version = "1.0"
    msg.header.incrementality = msg.header.FULL_DATASET
    msg.header.timestamp = int(time.time())
#    msg.header.timestamp = long(siri_data['serviceDelivery']['responseTimestamp'])

    for i, vehicle in enumerate(siri_data['serviceDelivery']['estimatedTimetableDelivery']):
        route_id = vehicle['lineRef']['value'][:6].strip()

        if len(vehicle['datedVehicleJourneyRef']) > 0:
            operator = vehicle['datedVehicleJourneyRef'].split('[:.]')
            if operator[0] == "RATP":
                sens = operator[4]
                if operator[4] == "A":
                    ent.trip_update.trip.direction_id = 0
                if operator[4] == "R":
                    ent.trip_update.trip.direction_id = 1

            if operator[0] != "RATP":
                continue
#        direction = vehicle['monitoredVehicleJourney']['directionRef'] # Il faudra editer le code pour le definir pour les autres...
#        ent.trip_update.trip.direction_id = int(direction) - 1 # Il faudra editer le code pour le definir pour les autres...

        if 'estimatedCalls' not in vehicle['monitoredVehicleJourney']:
            continue

        for call in vehicle['monitoredVehicleJourney']['estimatedCalls']:
            stoptime = ent.trip_update.stop_time_update.add()
            if 'stopPointRef' in vehicle['monitoredVehicleJourney']['estimatedCall']:
                stoptime.stop_id = vehicle['monitoredVehicleJourney']['estimatedCall']['stopPointRef']
            arrival_time = (dateutil.parser.parse(call['expectedArrivalTime']) - EPOCH).total_seconds()
            stoptime.arrival.time = int(arrival_time)
            departure_time = (dateutil.parser.parse(call['expectedDepartureTime']) - EPOCH).total_seconds()
            stoptime.departure.time = int(departure_time)

        ent = msg.entity.add() # On garde ca ?
        ent.id = str(i) #
        ent.trip_update.timestamp = vehicle['recordedAtTime'] #
        ent.trip_update.trip.route_id = route_id #

#        try:
#            int(vehicle['MonitoredVehicleJourney']['Delay'])
#        except:
#            print_exc()
#            print vehicle, vehicle['MonitoredVehicleJourney']['Delay']

#            continue

#        ent.trip_update.trip.start_date = vehicle['MonitoredVehicleJourney']['FramedVehicleJourneyRef']['DataFrameRef']['value'].replace("-", "")
#        if 'datedVehicleJourneyRef' in vehicle['monitoredVehicleJourney']['framedVehicleJourneyRef']: # doesn't exist in our feed
#            start_time = vehicle['monitoredVehicleJourney']['framedVehicleJourneyRef']['datedVehicleJourneyRef']
#            ent.trip_update.trip.start_time = start_time[:2]+":"+start_time[2:]+":00"
#
#
#        if 'vehicleRef' in vehicle['monitoredVehicleJourney']: # doesn't exist in our feed
#            ent.trip_update.vehicle.label = vehicle['monitoredVehicleJourney']['vehicleRef']['value']

    return msg

不幸的是,

此循环不起作用,返回错误,而它应该遍历以{"lineRef"开头的每个项目:

File "/home/nicolas/packaging/stif.py", line 24, in handle_siri operator = vehicle['datedVehicleJourneyRef'].split('[:.]') AttributeError: 'dict' object has no attribute 'split'

你可以帮我解决这个问题吗?

感谢您查看此内容。

2 个答案:

答案 0 :(得分:0)

JSON文件很棘手。我用Scratch文件做了类似的事情 https://gist.github.com/doyousketch2/8c1d07923554c78ed888b089e45536e2
这将为您提供钥匙和参赛作品 如果您需要更多帮助来确定如何解析这些,请回复。

#!/usr/bin/python3
# -*- coding: utf-8 -*-
##=========================================================
##  SiriJsonExtract.py  ~~~~~~~~~~~~~~~~~~~~~  17 Mar, 2017
##
##  Eli Innis
##  Twitter:  @ Doyousketch2
##  Email:  Doyousketch2 @ yahoo.com
##  GNU GPLv3  gnu.org/licenses/gpl-3.0.html
##=========================================================
##  libs  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

import json               ##  convert .json file into dicts

##=========================================================
##  vars  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

defaultDir  = '/home/eli/Programming/Python/siri/'
siri  = 'siri.json'
msg = []

##=========================================================
##  open file  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

with open((defaultDir + siri), 'r') as data:               ##  "with" is Python's crash resistant file open
    jay = json .load(data)                                 ##  load JSON file into the variable jay

##==============================================
##  In order to use a JSON file, we need to traverse down it's branches.
##  I modified code that was intended for recursive printing:
##  code.activestate.com/recipes/578094-recursively-print-nested-dictionaries

##  'item' is the item we are currently scanning
##  'depth' is how far we are within it, ie  this[0] [1] [2] [3]
##  'key' is used for dictionaries, so we can get the correct values associated with that particular key

def scan(item, depth = 0, key = ''):
    global msg
    tabs = lambda n: ' ' * n                               ##  simple spaces will suffice for tabs

    if isinstance(item, dict):                             ##  if we have a dictionary entry
        for key, value in sorted(item .items()):           ##  iterate through keys & values
            msg .append(tabs(depth) + 'key:   %s' % key)
            scan(value, depth + 2, key)                    ##  scan deeper

    elif isinstance(item, list):                           ##  if we have a list entry
        for listitem in item:                              ##  iterate through list items
            scan(listitem, depth + 2)                      ##  go even deeper in this list

    else:                                                  ##  can't go down. number, boolean, or empty set
        msg .append(tabs(depth) + 'item:   %s\n' % item)   ##  append the command or arg,  with a bit of padding,
                                                           ##  so the next one we paste doesn't collide.
    return msg

##==============================================
##  main  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

scan(jay)  ##  begin our scan here

text = '\n' .join(msg)
print(text)

##==============================================
##  eof  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

答案 1 :(得分:0)

在第一个答案中,它更容易看到它如何迭代JSON条目。
这里变得更加复杂。其中一半是法语 我父亲说法语,但我只听过点点滴滴。

如果我能看到所需的输出效果会有所帮助 我不知道RATP是什么。这似乎是公交时刻表?
我不知道为什么一切都会变成秒。

你能写一篇关于你想要输出的粗略草图吗?

#!/usr/bin/python3
# -*- coding: utf-8 -*-
##=========================================================
##  SiriJsonExtract.py  ~~~~~~~~~~~~~~~~~~~~~  17 Mar, 2017
##
##  Eli Innis
##  Twitter:  @ Doyousketch2
##  Email:  Doyousketch2 @ yahoo.com
##
##  GNU GPLv3  gnu.org/licenses/gpl-3.0.html
##
##=========================================================
##  libs  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

import datetime
import time
import pytz
import json
from dateutil.parser import parse

##=========================================================
##  vars  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

defaultDir  = '/home/eli/Programming/Python/siri/'
siri  = 'siri.json'

##=========================================================
##  global placeholder

msg = []

##=========================================================
##  open file  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

with open((defaultDir + siri), 'r') as data:               ##  "with" is Python's crash resistant file open
    jay = json .load(data)                                 ##  load JSON file into the variable jay

##=========================================================
##  scan funct  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

def scan(item, depth = 0, key = ''):
    global msg
    EPOCH = datetime.datetime(1970, 1, 1, tzinfo=pytz.utc)
    # stoptime = ent.trip_update.stop_time_update.add()
    tabs = lambda n: ' ' * n                               ##  simple spaces will suffice for tabs

    if isinstance(item, dict):                             ##  if we have a dictionary entry
        for key, value in sorted(item .items()):           ##  iterate through keys & values
            if key .endswith('ArrivalTime') :
                msg .append(tabs(depth) + 'Arrival:   %s  Time: %s' % (key, parse(value)))
                arrival_time = (parse(value) - EPOCH).total_seconds()
                # stoptime.arrival.time = int(arrival_time)

            elif key .endswith('DepartureTime') :
                msg .append(tabs(depth) + 'Departure:   %s  Time: %s' % (key, parse(value)))
                departure_time = (parse(value) - EPOCH).total_seconds()
                # stoptime.departure.time = int(departure_time)

            elif key == 'recordedAtTime':
                msg .append(tabs(depth) + 'recordedAtTime:   %s' % parse(value))

            elif key .startswith('datedVehicle'):
                msg .append(tabs(depth) + 'Operator:   %s' % value['value'])

            elif key == 'originName':
                if len(value) > 0:
                    msg .append(tabs(depth) + 'originName:   %s' % value[0]['value'])

            elif key == 'originRef':
                if len(value) > 0:
                    msg .append(tabs(depth) + 'originRef:   %s' % value['value'])

            elif key == 'directionName':
                if len(value) > 0:
                    msg .append(tabs(depth) + 'directionName:   %s' % value[0]['value'])

            elif key == 'publishedLineName':
                msg .append(tabs(depth) + 'publishedLineName:   %s' % value[0]['value'])

            elif key == 'destinationName':
                msg .append(tabs(depth) + 'destinationName:   %s' % value[0]['value'])

            elif key == 'destinationRef':
                msg .append(tabs(depth) + 'destinationRef:   %s' % value['value'])

            elif key == 'operatorRef':
                if len(value) > 0:
                    msg .append(tabs(depth) + 'operatorRef:   %s' % value['value'])

            elif key == 'vehicleMode':
                if len(value) > 0:
                    msg .append(tabs(depth) + 'vehicleMode:   %s' % value[0])

            elif key == 'lineRef':
                msg .append(tabs(depth) + 'lineRef:   %s' % value['value'])

            elif key == 'vehicleJourneyName':
                if len(value) > 0:
                    msg .append(tabs(depth) + 'vehicleJourneyName:   %s' % value[0]['value'])

            elif key == 'firstOrLastJourney':
                if len(value) > 0:
                    msg .append(tabs(depth) + 'firstOrLastJourney:   %s' % value)

            elif key == 'stopPointRef':
                if len(value) > 0:
                    msg .append(tabs(depth) + 'stopPointRef:   %s' % value['value'])

            elif key == 'producerRef':
                if len(value) > 0:
                    msg .append(tabs(depth) + 'producerRef:   %s' % value)

            elif key .endswith('Timestamp'):
                msg .append(tabs(depth) + '%s:   %s' % (key, parse(value)))

            elif key == 'status':
                if len(value) > 0:
                    msg .append(tabs(depth) + 'status:   %c' % value[0])

            elif key == 'value':
                msg .append(tabs(depth) + 'Value:   %s' % value)

            else:
                msg .append(tabs(depth) + 'key:   %s' % key)
                scan(value, depth + 2, key)                ##  scan deeper

    elif isinstance(item, list):                           ##  if we have a list entry
        for listitem in item:                              ##  iterate through list items
            scan(listitem, depth + 2)                      ##  go even deeper in this list

    else:                                                  ##  can't go down. number, boolean, or empty set
        msg .append(tabs(depth) + 'item:   %s\n' % item)   ##  append the command or arg,  with a bit of padding,
                                                           ##  so the next one we paste doesn't collide.
    return msg

##=========================================================
##  main    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

scan(jay)  ##  begin our scan here

text = '\n' .join(msg)
print(text)

##=========================================================
##  eof  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~