如何使用Python向JSON添加换行符函数

如何使用Python向JSON添加换行符函数,python,json,Python,Json,我有一个JSON,我必须对它进行操作,代码如下所示。我不得不操纵数据,因为上传到BigQuery时无法使用的数据部分无效 import json with open('firetobq_peripheral.json', 'r') as in_file: dicts = [] for line in in_file.readlines() : d = json.loads(line.strip()) if d.get('Peripherals'

我有一个JSON,我必须对它进行操作,代码如下所示。我不得不操纵数据,因为上传到BigQuery时无法使用的数据部分无效

import json

with open('firetobq_peripheral.json', 'r') as in_file:
    dicts = []
    for line in in_file.readlines() : 
        d = json.loads(line.strip())
        if d.get('Peripherals'): 
            del d['Peripherals']
        dicts += [d]

with open('firetobq_peripheral5.json', 'w') as out_file:
    out_file.write(json.dumps(dicts))
    out_file.write("\n")
然而,
out\u file.write(“\n”)
并没有像我之前处理的JSON那样,让JSON将每组数据写入换行符中。有人知道为什么会发生这种情况,以及如何避免这种情况吗?谢谢你的帮助

我需要数据像这样呈现

{"AppName": "DataWorks", "foundedPeripheralCount": 1, "version": "1.6.1(8056)", "deviceType": "iPhone 6", "createdAt": "2017-04-05T07:05:30.408Z", "updatedAt": "2017-04-05T07:08:49.569Z",  "connectedPeripheralCount": 1, "iOSVersion": "10.2.1"}
{"objectId": "20H5Hg2INB", "foundedPeripheralCount": 0, "DeviceVendorID": "5B7F085E-B3B6-4270-97DC-F42903CDEAC1", "version": "1.3.5(5801)", "deviceType": "iPhone 6", "createdAt": "2015-11-10T06:16:45.459Z", "updatedAt": "2015-11-10T06:16:45.459Z", "connectedPeripheralCount": 0, "iOSVersion": "9.1"}
{"AppName": "DataWorks", "foundedPeripheralCount": 2, "version": "1.6.2(8069)", "deviceType": "iPhone 6s", "createdAt": "2017-04-12T10:05:05.937Z", "updatedAt": "2017-07-06T07:33:02.006Z", "connectedPeripheralCount": 8, "iOSVersion": "10.2.1"}

如果您希望完全按照读取数据的方式写入数据,则需要在
dicts
中迭代每个字典:

with open('firetobq_peripheral5.json', 'w') as out_file:
    for d in dicts:
        out_file.write(json.dumps(d))
        out_file.write("\n")

如果这不是必需的,那么
json.dump
将是最好的选择。

我认为您应该这样做
out\u文件。write(\\n”)
您可以提供一个包含一些数据的示例吗?我已经添加了一个示例
with open("some_file.json", "w") as f: 
    f.write( 
        json.dumps(array_of_dictionaries).replace("},", "},\n")
    )