Мне удалось вызвать API и получить ответ, но у меня возникли проблемы с преобразованием строки JSON в объект словаря Python, поэтому я могу разобрать ее.
Пример JSON string:
{
"target": {
"icao_address": "C032A2",
"timestamp": "2020-02-13T22:44:39Z",
"latitude": 50.723694,
"longitude": -114.63788,
"altitude_baro": 13225,
"heading": 40.0,
"ground_speed": 340.0,
"vertical_rate": -2360,
"squawk_code": "6616",
"on_ground": false,
"callsign": "WEN3627",
"tail_number": "C-FTEN",
"collection_type": "terrestrial",
"flight_number": "WR3627",
"origin_airport_iata": "PDX",
"destination_airport_iata": "YYC"
}
}{
"target": {
"icao_address": "AB35D8",
"timestamp": "2020-02-13T22:44:42Z",
"latitude": 33.69842,
"longitude": -111.896725,
"altitude_baro": 4325,
"heading": 260.0,
"ground_speed": 90.0,
"vertical_rate": -250,
"on_ground": false,
"callsign": "MSQT356",
"tail_number": "N821PA",
"collection_type": "terrestrial"
}
}{
Код, который я использую, я могу распечатать строку JSON, открыв ее файл, но не могу получить к ней доступ как словарь. В идеале я просто пытаюсь подсчитать количество разных словарей в строке JSON.
#call datastream and output to new file
def call_stream(self):
try:
#paramaters for call
headers = {'Content-Type': 'application/json','Authorization': 'Bearer {0}'.format(self.token)}
timeout = time.time() + self.timeout
#calling datastream
with requests.get(self.url, headers=headers, stream=True) as r:
with open('datastream:' + self.get_time() + '.json', 'w') as json_file:
global target_updates_count
global terrestrial_count
global satellite_count
global FILENAME
FILENAME.append(json_file.name)
#reading through JSON hashtables
for line in r.iter_lines(decode_unicode=True):
target_updates_count += 1
if time.time() < timeout:
msg = json.loads(line)
json_pprint = json.dumps(msg)
json_file.write(json_pprint)
#looping through dict objects and counting useful statistics for target_updates
data = msg['target']
for key in data:
if key == 'collection_type' and data[key] == 'terrestrial':
terrestrial_count += 1
elif key == 'collection_type' and data[key] == 'satellite':
satellite_count += 1
else:
r.close()
except AttributeError:
pass