【问题标题】:Convert Multiple JSON Objects to JSON Array将多个 JSON 对象转换为 JSON 数组
【发布时间】:2017-12-22 20:21:35
【问题描述】:

我从数据源生成了一个 JSON 文件,格式为。
{}{}{}
我希望将此格式转换为逗号分隔的 JSON 数组。 [{},{},{}].
最终目标是将 JSON 数据 [{},{},{}] 推送到 MongoDB。 我的 pythoin 解决方案(虽然很幼稚)看起来像这样:

def CreateJSONArrayFile(filename):
 print('Opening file with JSON data')
 with open(filename) as data_file:
    raw_data = data_file.read()
    tweaked_data = raw_data.replace('}{', '}^|{')
 split_data = tweaked_data.split('^|')
 outfile = open('split_data.json', 'w')
 outfile.write('[')
 for item in split_data:
    outfile.write("%s," % item)
 outfile.write(']')
 print('split_data.json Created with JSON Array')

上面的代码给了我错误的结果。 你能帮我优化解决方案吗?如果您需要更多详细信息,请告诉我。

【问题讨论】:

  • 你能转换成字典,遍历键/值对,然后转换回 JSON 吗? (或作为 dicts 离开)。为了获得最好的帮助,您能否提供一个简化的来源和结果示例?
  • 由于您从数据源生成了这个{}{}{} 格式,可能最简单的方法是从数据源生成desired 格式,将每个dict 附加到@ 987654327@ -- 而不是麻烦重新格式化不需要的格式

标签: json mongodb python-3.x


【解决方案1】:

我在这个问题上持谨慎态度,但如果不是一个选项 - 我认为这会让你得到你想要的。

myJson = """{"This": "is", "a": "test"} {"Of": "The", "Emergency":"Broadcast"}"""
myJson = myJson.replace("} {", "}###{")
new_list = myJson.split('###')
print(new_list)

产量:

['{"This": "is", "a": "test"}', '{"Of": "The", "Emergency":"Broadcast"}']

不是说这是最优雅的方式:)

【讨论】:

    猜你喜欢
    • 2020-10-04
    • 2012-07-21
    • 2020-10-02
    • 1970-01-01
    • 2018-10-11
    • 1970-01-01
    • 2018-04-16
    • 1970-01-01
    相关资源
    最近更新 更多