【问题标题】:Add JSON key names to json values in an array. File contains bulk JSONs [closed]将 JSON 键名添加到数组中的 json 值。文件包含批量 JSON [关闭]
【发布时间】:2021-11-21 18:09:22
【问题描述】:

我有一个包含 json 列表(超过 10k)的文件,类似这样

{"name":"abc", "location": {"coordinates": [-94.350096,39.049484]}} 
{"name":"xyz", "location": {"coordinates": [-91.350096,36.049484]}} 
{"name":"lmn", "location": {"coordinates": [-84.350096,69.049484]}} 
{"name":"pqr", "location": {"coordinates": [-90.350096,31.049484]}}

我想将其转换为以下内容

{"name":"abc", "location": {"coordinates": ["latitude":-94.350096,"longitude":39.049484]}} 
{"name":"xyz", "location": {"coordinates": ["latitude":-91.350096,"longitude":36.049484]}}
{"name":"lmn", "location": {"coordinates": ["latitude":-84.350096,"longitude":69.049484]}} 
{"name":"pqr", "location": {"coordinates": ["latitude":-90.350096,"longitude":31.049484]}}

对任何此类代码的任何引用?

【问题讨论】:

  • 如果只需要添加“纬度”和“经度”这两个词,那么可以使用notepad++编辑器添加。如果你想要编程的结果,请告诉。
  • 您的示例不是有效的 JSON。只有对象 ({}) 有键。
  • @Pran Sukh - 我有 MAC。无论哪种方式都可以,编程或mac支持的工具
  • @user837593 我刚刚在 youtube 上创建了一个视频。这是链接youtu.be/nXYQEEePuSI

标签: python java arrays json


【解决方案1】:

逐行读取文件并使用json模块将其加载为dict。最后,根据需要进行编辑。

import json
with open("test.txt") as f:
    for line in f:
        data = json.loads(line)
        coords = data["location"]["coordinates"]
        data["location"]["coordinates"] = {"latitute": coords[0], "longitude": coords[1]}
        print(data)

【讨论】:

  • 请注意,此答案仅将 json 格式数据的行打印到控制台。但是,这仍然可以通过管道传输到新文件。
  • @Eshwar S R - 非常感谢您的意见。我是 Python 新手。可以“json.loads(line)”加载 733MB 大小的文件。它有 85k 条记录。如果不是正确的方法
  • 我们不会一次性加载整个文件。我们正在加载每一行,它本身就是一个 json。
  • 文件中有 85k 行。我正在尝试修改每一行,然后将其写入文件。它停在 2130 行号并给出以下错误。 "文件 "json_replace.py",第 9 行,在 coords = data["location"]["coordinates"] TypeError: 'NoneType' object is not subscriptable"。我根据上面的评论尝试的代码在下面的评论中编辑
  • import json jsonFile = open("locator_latlong.json", "a") i=0; with open("locator.json") as f: for line in f: # print(line) data = json.loads(line) coords = data["location"]["coordinates"] # print(coords); data["location"]["coordinates"] = {"latitude": coords[0], "longitude": coords[1]} i=i+1; print(i, data) jsonString = json.dumps(data) jsonFile.write(jsonString) jsonFile.write('\n') jsonFile.close()
猜你喜欢
  • 2014-10-04
  • 2017-10-17
  • 1970-01-01
  • 2019-08-28
  • 1970-01-01
  • 1970-01-01
  • 2013-10-15
  • 2013-02-15
  • 2018-08-05
相关资源
最近更新 更多