我已经能够调用一个api并获得响应,但是在将JSON字符串转换为Python字典对象时遇到了麻烦,因此我可以通过它进行解析。
JSON字符串示例:
{
"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字符串,但无法将其作为字典进行访问。理想情况下,我只是想计算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