我有一个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_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"}
答案 0 :(得分: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
将是最佳选择。
答案 1 :(得分:0)
with open("some_file.json", "w") as f:
f.write(
json.dumps(array_of_dictionaries).replace("},", "},\n")
)