如何格式化API JSON输出?

时间:2019-06-10 00:00:07

标签: python json python-2.7 tkinter

我最近开始研究在Tkinter的python程序中使用API​​,到目前为止,我已经能够编写一个程序,在伦敦地铁站的旅行计划器中使用TransportAPI提取旅行数据。

到目前为止,该程序运行良好,唯一的问题是将返回的JSON数据格式化为用户可读的格式。下面是创建URL并在程序中显示输出的函数代码以及程序运行时的当前输出。

创建API URL并返回输出:

(defun remove-equals (sequence &key (test #'eql) (start 0) end (key #'identity))
  "Removes all repetitive sequence elements based on equality test."
  #.(defun equality-test (x y)
      (funcall test (funcall key x) (funcall key y)))
  #.(sb-ext:define-hash-table-test equality-test sxhash)
  (let ((ht (make-hash-table :test #'equality-test)))
    (iterate (for elt in-sequence (subseq sequence start end))
             (incf (gethash (funcall key elt) ht 0)))
    (remove-if (lambda (elt)
                 (/= 1 (gethash elt ht)))
               sequence :start start :end end :key key)))

在程序窗口中显示输出:

def create_url(): # creates API url using inputted / chosen values

    input_time = get_time()
    input_date = get_date()

    station_from = get_source()
    station_to = get_destination()

    search_url = 'https://transportapi.com/v3/uk/public/journey/from/'+station_from+'/to/'+station_to+'/at/'+input_date+'/'+input_time+'.json?app_id=bab9c3cc&app_key=0caef97a7e642a7d15f6f59efac6332c&modes=train&not_modes=bus-boat&service=tfl'

    return search_url

程序中的当前输出:

def display_results(): # displays API result to the user
    data = get_data()
    label_search_result.config(text=data)

我将如何将这些数据格式化为用户更易读的格式?对于一个想法,理想的输出应该是这样的:

{"request_time":"2019-06-10T00:50:45+01:00","source":"TfL journey planning
API","acknowledgements":"Transport for London","routes":
[{"duration":"00:09:00","route_parts":
[{"mode":"tube","from_point_name":"Stratford","to_point_name":"Liverpool
Street","destination":"Ealing
Broadway","line_name":"Central","duration":"00:09:00","departure_time":"12:46"
,"arrival_time":"12:55","coordinates":[[-0.00336,51.54171],[-0.00427,51.54114],[-0.00474,51.54078],[-0.00561,51.54003],[-0.00758,51.53835],[-0.00955,51.53671],[-0.01158,51.53537],[-0.01786,51.53208],[-0.01984,51.53117],[-0.02096,51.53064],[-0.0214,51.53037],[-0.0253,51.52724],[-0.02583,51.52699],[-0.02626,51.52688],[-0.02806,51.52654],[-0.03209,51.52567],[-0.03299,51.52548],[-0.03354,51.52533],[-0.03354,51.52533],[-0.03509,51.52494],[-0.03592,51.5247],[-0.0374,51.52418],[-0.03905,51.52366],[-0.04055,51.52328],[-0.04125,51.52314],[-0.04253,51.52314],[-0.04328,51.52324],[-0.04472,51.5236],[-0.0457,51.52393],[-0.04659,51.52435],[-0.04945,51.52616],[-0.04996,51.52643],[-0.05064,51.52665],[-0.0516,51.52684],[-0.05459,51.52706],[-0.05459,51.52706],[-0.0568,51.52722],[-0.05741,51.52722],[-0.062,51.52673],[-0.06601,51.52627],[-0.06796,51.526],[-0.06924,51.52575],[-0.07011,51.52552],[-0.07173,51.5248],[-0.07397,51.52386],[-0.0751,51.52336],[-0.0762,51.52271],[-0.08219,51.51805]]}],"departure_time":"12:46","departure_date":"2019-07-07","arrival_time":"12:55","arrival_date":"2019-07-07"},{"duration":"00:09:00","route_parts":[{"mode":"tube","from_point_name":"Stratford","to_point_name":"Liverpool Street","destination":"West Ruislip","line_name":"Central","duration":"00:09:00","departure_time":"12:48","arrival_time":"12:57","coordinates":[[-0.00336,51.54171],[-0.00427,51.54114],[-0.00474,51.54078],[-0.00561,51.54003],[-0.00758,51.53835],[-0.00955,51.53671],[-0.01158,51.53537],[-0.01786,51.53208],[-0.01984,51.53117],[-0.02096,51.53064],[-0.0214,51.53037],[-0.0253,51.52724],[-0.02583,51.52699],[-0.02626,51.52688],[-0.02806,51.52654],[-0.03209,51.52567],[-0.03299,51.52548],[-0.03354,51.52533],[-0.03354,51.52533],[-0.03509,51.52494],[-0.03592,51.5247],[-0.0374,51.52418],[-0.03905,51.52366],[-0.04055,51.52328],[-0.04125,51.52314],[-0.04253,51.52314],[-0.04328,51.52324],[-0.04472,51.5236],[-0.0457,51.52393],[-0.04659,51.52435],[-0.04945,51.52616],[-0.04996,51.52643],[-0.05064,51.52665],[-0.0516,51.52684],[-0.05459,51.52706],[-0.05459,51.52706],[-0.0568,51.52722],[-0.05741,51.52722],[-0.062,51.52673],[-0.06601,51.52627],[-0.06796,51.526],[-0.06924,51.52575],[-0.07011,51.52552],[-0.07173,51.5248],[-0.07397,51.52386],[-0.0751,51.52336],[-0.0762,51.52271],[-0.08219,51.51805]]}],"departure_time":"12:48","departure_date":"2019-07-07","arrival_time":"12:57","arrival_date":"2019-07-07"}]}

3 个答案:

答案 0 :(得分:1)

原始JSON数据的格式如下所示,因此更具可读性,您可以看到其结构更清晰-这在进行此类操作时通常很有帮助:

{"acknowledgements": "Transport for London",
 "request_time": "2019-06-10T00:50:45+01:00",
 "routes": [{"arrival_date": "2019-07-07",
             "arrival_time": "12:55",
             "departure_date": "2019-07-07",
             "departure_time": "12:46",
             "duration": "00:09:00",
             "route_parts": [{"arrival_time": "12:55",
                              "coordinates": [[-0.00336, 51.54171],
                                               .
                                               .
                                               .
                                              [-0.08219, 51.51805]],
                              "departure_time": "12:46",
                              "destination": "Ealing Broadway",
                              "duration": "00:09:00",
                              "from_point_name": "Stratford",
                              "line_name": "Central",
                              "mode": "tube",
                              "to_point_name": "Liverpool Street"}]},
            {"arrival_date": "2019-07-07",
             "arrival_time": "12:57",
             "departure_date": "2019-07-07",
             "departure_time": "12:48",
             "duration": "00:09:00",
             "route_parts": [{"arrival_time": "12:57",
                              "coordinates": [[-0.00336, 51.54171],
                                               .
                                               .
                                               .
                                              [-0.08219, 51.51805]],
                              "departure_time": "12:48",
                              "destination": "West Ruislip",
                              "duration": "00:09:00",
                              "from_point_name": "Stratford",
                              "line_name": "Central",
                              "mode": "tube",
                              "to_point_name": "Liverpool Street"}]}],
 "source": "TfL journey planning API"}

您可以使用json.loads()将字符串从API转换为Python字典,然后,对其内容进行迭代,并将键和值放入所需的格式:

import json

data = json.loads(get_data())

for route in data['routes']:
    for route_part in route['route_parts']:
        print('Source:', route_part['from_point_name'])
        print('Route:')
        print('Line:', route_part['line_name'])
        print('To:', route_part['destination'])
        print('Duration:', route_part['duration'])
        # etc ...

        print()  # Blank line.

答案 1 :(得分:0)

要做的第一件事是使用JSON模块将JSON字符串解析为dict

import json

data = json.loads(get_data())

从现在开始,您可以像使用任何字典一样获取数据,并使用其格式化字符串。例如:

pretty_data = ""
for route in data["routes"]:
    pretty_data += """Source: {}
Destination: {}

...""".format(route["route_parts"][0]["from_point_name"], route["route_parts"][-1]["to_point_name"])

答案 2 :(得分:0)

希望这会有所帮助,“数据”应该是从JSON解析的字典。

data = json_dictionary


print ('Request Time: ' + data['request_time'])
print ('Source: ' + data['source'])
print ('Acknowledgements: ' + data['acknowledgements'])
print ()


for x in (data['routes']):

    for y in x['route_parts']:

        print ('Departure Date: ' + x['departure_date'])
        print ('From Point Name: ' + y['from_point_name'])
        print ('To Point Name: ' + y['to_point_name'])
        print ('Destination: ' + y['destination'])
        print ('Line Name: ' + y['line_name'])
        print ('Duration: ' + y['duration'])
        print ('Departure Time: ' + y['departure_time'])
        print ('Duration: ' + y['duration'])
        print ('Arrival Time: ' + y['arrival_time'])

        #for z in y['coordinates']:
        #    print ('Coordinates' + z)

        print ()

输出:

Request Time: 2019-06-10T00:50:45+01:00
Source: TfL journey planning API
AcknowledgementsTransport for London

Departure Date: 2019-07-07
From Point Name: Stratford
To Point Name: Liverpool Street
Destination: Ealing Broadway
Line Name: Central
Duration: 00:09:00
Departure Time: 12:46
Duration: 00:09:00
Arrival Time: 12:55

Departure Date: 2019-07-07
From Point Name: Stratford
To Point Name: Liverpool Street
Destination: West Ruislip
Line Name: Central
Duration: 00:09:00
Departure Time: 12:48
Duration: 00:09:00
Arrival Time: 12:57