2017-07-26 15 views
0

私は操作しなければならないJSONを持っています。 BigQueryにアップロードする際に使用できなかったデータの一部が無効であるため、データを操作する必要がありました。Pythonを使用してJSONに改行関数を追加する方法

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")はそれが私が働いている以前のJSONsに持っているようJSONは改行でデータの各セットを記述することはありません。なぜこれが起こっているのか、これを回避する方法を誰かが知っていますか?助けてくれてありがとう。

私はあなたがそれを読んでいるように正確にデータを書き込みたい場合は、あなたがdictsに各辞書を反復する必要がありますデータはこの

{"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

あなたはこのようにすべきだと思います。out_file.write( "\\ n") ' – Sankar

+0

あなたはいくつかのデータを[mcve]に渡してください。 –

+0

私は例を追加しました –

答えて

1

のように提示する必要があります

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が最適です。

関連する問題