Извлечь значение в Python - PullRequest
0 голосов
/ 19 февраля 2020

Мой код:

import requests
import json

web_page = requests.get("http://api.bart.gov/api/etd.aspx?cmd=etd&orig=mont&key=MW9S-E7SL-26DU-VV8V&json=y")
response = web_page.text
parsed_json = json.loads(response)
#print(parsed_json)

print(parsed_json['root']['date'])
print(parsed_json['root']['time'])
print(parsed_json['root']['station']['name'])

Как извлечь значение пункта назначения и минут снизу в Python.

[{'name': 'Montgomery St.', 'abbr': 'MONT', 'etd': [{'destination': 'Daly City', 'abbreviation': 'DALY', 'limited': '0', 'estimate': [{'minutes': '39', 'platform': '1', 'direction': 'South', 'length': '10', 'color': 'WHITE', 'hexcolor': '#ffffff', 'bikeflag': '1', 'delay': '220'}]}, {'destination': 'SF Airport', 'abbreviation': 'SFIA', 'limited': '0', 'estimate': [{'minutes': '16', 'platform': '1', 'direction': 'South', 'length': '10', 'color': 'YELLOW', 'hexcolor': '#ffff33', 'bikeflag': '1', 'delay': '132'}, {'minutes': '26', 'platform': '1', 'direction': 'South', 'length': '10', 'color': 'BLUE', 'hexcolor': '#0099cc', 'bikeflag': '1', 'delay': '69'}]}]}]

Ответы [ 4 ]

2 голосов
/ 19 февраля 2020

Попробуйте:

json_obj = {'name': 'Montgomery St.', 'abbr': 'MONT', 'etd': [{'destination': 'Antioch', 'abbreviation': 'ANTC', 'limited': '0', 'estimate': [{'minutes': '1', 'platform': '2', 'direction': 'North', 'length': '10', 'color': 'YELLOW', 'hexcolor': '#ffff33', 'bikeflag': '1', 'delay': '254'}]}, 

{'destination': 'Daly City', 'abbreviation': 'DALY', 'limited': '0', 'estimate': [{'minutes': '39', 'platform': '1', 'direction': 'South', 'length': '0', 'color': 'BLUE', 'hexcolor': '#0099cc', 'bikeflag': '1', 'delay': '0'}]}, 

{'destination': 'SF Airport', 'abbreviation': 'SFIA', 'limited': '0', 'estimate': [{'minutes': '38', 'platform': '1', 'direction': 'South', 'length': '10', 'color': 'YELLOW', 'hexcolor': '#ffff33', 'bikeflag': '1', 'delay': '0'}]}]}

for item in json_obj['etd']:
    dest = item['destination']
    minute = item['estimate'][0]['minutes']
    print(dest, minute)

Вывод:

Antioch 1
Daly City 39
SF Airport 38
1 голос
/ 19 февраля 2020

Проблема в parsed_json['root']['station']['name']. parsed_json['root']['station'] - это список, а не диктат, поэтому он не имеет ключа name. Вам нужно использовать индекс 0 или перебрать его

for station in parsed_json['root']['station']:
    for etd in station['etd']:
        for estimate in etd['estimate']:
            print(etd['destination'], estimate['minutes'])

Вывод

Daly City 35
SF Airport 16
SF Airport 26
1 голос
/ 19 февраля 2020

Попробуйте получить json данные:

import json

# some JSON:
json_data= {'destination': 'Daly City', 'abbreviation': 'DALY', 'limited': '0', 'estimate': [{'minutes': '39', 'platform': '1', 'direction': 'South', 'length': '0', 'color': 'BLUE', 'hexcolor': '#0099cc', 'bikeflag': '1', 'delay': '0'}]}

# parse json_data:
data = json.dumps(json_data)
extract_json = json.loads(data)

print("Destination: "+extract_json["destination"])
print("Minutes: "+extract_json["estimate"][0]["minutes"])

Вывод:

Destination: Daly City
Minutes: 39
1 голос
/ 19 февраля 2020

Предполагая, что данные находятся в d_MONT:

d_MONT = {'name': 'Montgomery St.', 'abbr': 'MONT', 'etd': [{'destination': 'Antioch', 'abbreviation': 'ANTC', 'limited': '0', 'estimate': [{'minutes': '1', 'platform': '2', 'direction': 'North', 'length': '10', 'color': 'YELLOW', 'hexcolor': '#ffff33', 'bikeflag': '1', 'delay': '254'}]}, 

{'destination': 'Daly City', 'abbreviation': 'DALY', 'limited': '0', 'estimate': [{'minutes': '39', 'platform': '1', 'direction': 'South', 'length': '0', 'color': 'BLUE', 'hexcolor': '#0099cc', 'bikeflag': '1', 'delay': '0'}]}, 

{'destination': 'SF Airport', 'abbreviation': 'SFIA', 'limited': '0', 'estimate': [{'minutes': '38', 'platform': '1', 'direction': 'South', 'length': '10', 'color': 'YELLOW', 'hexcolor': '#ffff33', 'bikeflag': '1', 'delay': '0'}]}]}

Это найдет следующий поезд до пункта назначения. Обязательно:

destinationList = d_MONT['etd']

destinationRequired = 'Daly City'

for destinationDict in destinationList:
    if destinationDict['destination'] == destinationRequired:
        earliest = None
        for estimate in destinationDict['estimate']:
            if earliest is None or estimate['minutes'] < eariest:
                earliest = estimate['minutes']
        print("Next train to {0}: {1} minutes".format(destinationRequired, earliest))
        break

else:
    print("No trains to {0}".format(destinationRequired))

Обратите внимание, что есть еще Pythoni c способов сделать это, и приведенный выше пример кода не соответствует PEP8, но я думаю, что важно, чтобы вы понимали основы c logi c того, как делать то, что вы хотите, а не сложный Python однострочный.

Вы не документируете объектный формат JSON, поэтому я не думаю, что можно с уверенностью предположить, что список поездов до пункта назначения будет в порядке, поэтому самый безопасный - это пройти по каждому из них и найти самый ранний. Даже не ясно, будет ли в списке возвращено больше одного поезда, и в этом случае достаточно простого [0], а не проходить через каждый.

...