【问题标题】:Json to new-line delimited jsonJson 到换行符分隔的 json
【发布时间】:2021-03-22 05:23:46
【问题描述】:

我正在尝试将 Json 文件转换为 ndjson。我正在从 GCS(谷歌云存储)读取文件。 样本数据:

{
  "Item1" : "INT",
  "Item2" : "INT",
  "Item3" : "text",
  "Item4" : "text",
  "Item5" : "Date"
}{
  "Item1" : "INT",
  "Item2" : "INT",
  "Item3" : "text",
  "Item4" : "text",
  "Item5" : "Date"
}{
  "Item1" : "INT",
  "Item2" : "INT",
  "Item3" : "text",
  "Item4" : "text",
  "Item5" : "Date"
}

以下是我的代码。

bucket = client.get_bucket('bucket name')
# Name of the object to be stored in the bucket
object_name_in_gcs_bucket = bucket.get_blob('file.json')
object_to_string = object_name_in_gcs_bucket.download_as_string()
#json_data = ndjson.loads(object_to_string)
json_list = [json.loads(row.decode('utf-8')) for row in object_to_string.split(b'\n') if row]

我收到的错误位于 json_list: json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 3 (char 2)

需要的输出:

{"Item1" : "INT","Item2" : "INT","Item3" : "text","Item4" : "text","Item5" : "Date"}
{"Item1" : "INT","Item2" : "INT","Item3" : "text","Item4" : "text","Item5" : "Date"}
{"Item1" : "INT","Item2" : "INT","Item3" : "text","Item4" : "text","Item5" : "Date"}

【问题讨论】:

  • 我认为这可以帮助 stackoverflow.com/questions/51300674/… 。如果不是,您可能想要发布 object_to_string 值的示例。
  • 您的输入数据似乎不是有效的 JSON - 它需要围绕 [] 和 , 在每个 }{
  • 您的 JSON 无效。如果这是另一个工具的输出,请修复该工具。否则,您可以使用第一个答案之类的技巧(这将破坏更复杂的 JSON)或手动编辑文件以使其成为有效的 JSON。

标签: python json ndjson


【解决方案1】:

我认为您的主要问题是您在行尾而不是右大括号上拆分。这是一个完成我认为您正在尝试的示例。

from json import loads, dumps

with open("test.json") as f:
  file_string = f.read()
  dicts = [loads(f"{x}}}".replace("\n","")) for x in file_string.split("}")[0:-1]]
  for d in dicts:
    print(d)

with open("new.json", "a+") as newf:
  for d in dicts:
    newf.write(f"{dumps(d)}\n")

输出:

[root@foohome]# ./test.py
{'Item1': 'INT', 'Item2': 'INT', 'Item3': 'text', 'Item4': 'text', 'Item5': 'Date'}
{'Item1': 'INT', 'Item2': 'INT', 'Item3': 'text', 'Item4': 'text', 'Item5': 'Date'}
{'Item1': 'INT', 'Item2': 'INT', 'Item3': 'text', 'Item4': 'text', 'Item5': 'Date'}
[root@foo home]# cat new.json
{"Item1": "INT", "Item2": "INT", "Item3": "text", "Item4": "text", "Item5": "Date"}
{"Item1": "INT", "Item2": "INT", "Item3": "text", "Item4": "text", "Item5": "Date"}
{"Item1": "INT", "Item2": "INT", "Item3": "text", "Item4": "text", "Item5": "Date"}

【讨论】:

    猜你喜欢
    • 2021-12-07
    • 1970-01-01
    • 2018-12-20
    • 1970-01-01
    • 2015-12-21
    • 2018-04-03
    • 2015-05-12
    • 2015-07-10
    • 1970-01-01
    相关资源
    最近更新 更多