如何使用Python从JSON文档提取多字段?

时间:2020-06-03 14:33:03

标签: python json

我只需要从我的json文档中获取特定字段,即lat,long和timestamp。此json文件是RESTful API的结果。我遇到了如何仅解开一个领域的问题。

Json documet: {'info':{'satname':'SPACE STATION','satid':25544,'transactionscount': 0},'位置':[{'satlatitude':28.89539607,'satlongitude':90.44547739, '高度':420.36,'方位角':12.46,'海拔':-52.81,'ra': 215.55022984,'dec':-5.00234017,'timestamp':1591196844,'ecliped': True}]}

 Here is my try:

URL = "url"
def data_collection():
  data = requests.get(url = URL).json() 

  del data['positions'][1]

  print(data)
schedule.every(10).seconds.do(data_collection)


while True:
 schedule.run_pending()
 time.sleep(1) 

2 个答案:

答案 0 :(得分:2)

def data_collection():
  data = requests.get(url = URL).json() 
  print([ data['positions'][0][x] for x in ('satlatitude', 'satlongitude', 'timestamp') ])

答案 1 :(得分:2)

每次读取一个不同的字段时,您都在更改数据的值,据我从您的示例所知,JSON数据内没有列表,那么为什么要使用索引访问它?

更改您的代码

data = data['positions'][0]['lat']
data = data['positions'][1]['long']
data = data ['positions'][4]['timestamp']

lat = data['positions']['lat']
long = data['positions']['long']
timestamp = data ['positions']['timestamp']