遍历python中的json提要 [英] Iterate through a json feed in python
问题描述
我正在遍历这样的提要:
I'm iterating through such a 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脚本:
Using a python script:
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"
开头的每个项目:
This loop is not working, returning an error, while it should iterate through each item starting with {"lineRef"
:
File "/home/nicolas/packaging/stif.py", line 24, in handle_siri operator = vehicle['datedVehicleJourneyRef'].split('[:.]') AttributeError: 'dict' object has no attribute 'split'
您能帮我解决这个问题吗?
Could you please help me fix this?
感谢您的关注.
推荐答案
在第一个答案中,如何更轻松地查看它如何遍历JSON条目.
这里变得更加复杂.其中一半是法语.
我父亲说法语,但我只听过点点滴滴.
It's easier to see how it's iterating through the JSON entries in first answer.
It gets more complicated here. Half of it is in French.
My dad speaks French, but I've only ever heard bits and pieces.
如果我能看到所需的输出是什么样的,这将会有所帮助.
我不知道RATP是什么.这似乎是公交车时间表吗?
我不明白为什么一切都转换成秒.
It would help if I could see what the desired output would look like.
I don't know what RATP is. This seems to be a bus schedule?
I don't get why everything is converted into seconds.
您能写出您希望输出看起来如何的草稿吗?
Can you write up a rough-draft of how you want the output to look?
#!/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 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
这篇关于遍历python中的json提要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!