将多个JSON对象转换为JSON数组

时间:2017-12-22 20:21:35

标签: json mongodb python-3.x

我已经从格式化的数据源生成了一个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')

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

1 个答案:

答案 0 :(得分:0)

我和davedwards在这一个,但如果不是一个选项 - 我认为这可以让你得到你想要的。

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"}']

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