【问题标题】:How to create a new json field from another json key vaues with python?如何使用 python 从另一个 json 键值创建一个新的 json 字段?
【发布时间】:2020-06-05 03:43:39
【问题描述】:

我从 RESTful API 获得了经纬度。我需要从另一个 json 字段中创建新的 json 字段。

我的代码如下:

def collect_data():
  data = requests.get(url = URL).json() 
  del data['positions'][1]
  my_dict={}
  my_dict["satlatitude"]= data["positions"][0]["satlatitude"]
  my_dict["satlongitude"]= data["positions"][0]["satlongitude"]


  new_data = json.dumps(my_dict)
  new_data2 = {'geo' : {"lat": new_data["satlatitude"][0], "lon": new_data["satlatitude"][0]}} 
  es.index(index='satellitepositions', doc_type='satelitepos', body=new_data2)



schedule.every(10).seconds.do(collect_data)

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

我没有得到我所期望的。我需要的是: new_data2 = {'geo' : {"lat":satlatitude , "lon": satlongitude}} 这个satlatitude和satlongitude应该来自数据。我很困惑如何提取字段
来自 json 文档。 有人可以帮我解决这个问题吗?

RESTful 数据样本: Json 文档: {'info': {'satname': 'SPACE STATION', 'satid': 25544,
'transactionscount': 0}, '仓位': [{'satlatitude': 28.89539607,
'satlongitude': 90.44547739, 'sataltitude': 420.36, '方位角': 12.46,
“海拔”:-52.81,“ra”:215.55022984,“dec”:-5.00234017,“时间戳”: 1591196844, '黯然失色': True}]}

new_data2 = {'geo' : {"lat":28.89539607 , "lon": 90.44547739,}}

但是这些值每次都应该改变。

【问题讨论】:

  • 能否提供 requests 查询返回的数据示例?如果不了解您所操作的数据,就很难为您提供帮助。
  • 是的,我会给

标签: python json


【解决方案1】:

我认为问题源于这一行:

new_data = json.dumps(my_dict)

当你这样做时,你将你的 dict 转储到一个字符串中。您不能再通过 dict 键对其进行索引,它是一个字符串。

但是您稍后仍然尝试通过键对其进行索引:

new_data["satlatitude"][0]

这会崩溃。 new_data 是一个字符串。

不要开玩笑json.dumps。我相信您不需要将数据序列化回 JSON,elasticsearch 库会为您执行此操作。

解决办法:

这是(应该)有效的解决方案:

data = requests.get(URL).json() 

new_data = {'geo':{'lat':data['positions'][0]['satlatitude'],
                   'lon':data['positions'][0]['satlongitude']}}

es.index(index='satellitepositions', doc_type='satelitepos', body=new_data)

并不是说这没有验证请求已正确返回,或者其中的数据符合您的期望。如果您希望代码健壮,则应检查这些。

【讨论】:

  • 但是如何创建具有 lat 和 long 值的 'geo' 字段?
  • 我需要创建这个字段来创建索引
  • 我收到此错误 TypeError: list indices must be integers or slices, not str
  • 修复它并测试它。
  • 我收到以下错误,我知道不是因为这个,而是因为 Elasticsearch。如果你熟悉 ES 可以帮助我吗?我的错误是:RequestError: RequestError(400, 'mapper_parsing_exception', 'field must be either [lat], [lon] or [geohash]').如果需要我可以更新我的问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-12
  • 2018-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多