简体   繁体   English

将数据追加到现有的Json文件

[英]Appending data to an existing Json file

i have json file of the following format: 我有以下格式的json文件:

{"CustomerNo": "858017D", "SalesOrder": "ERI2380", "Brand": "HONAC", "Item": "HL10CESWB", "Qty": "1", "Month": "6","time": "2018-06-19T16:28:58Z"}
{"CustomerNo": "072881D", "SalesOrder": "W619091", "Brand": "HONAC", "Item": "MO10CESWK", "Qty": "-1", "Month": "6","time": "2018-06-08T12:36:29Z"}
{"CustomerNo": "072881D", "SalesOrder": "W642501", "Brand": "HONAC", "Item": "MO08CESWK", "Qty": "1", "Month": "6",  "time": "2018-06-19T08:20:51Z"}
{"CustomerNo": "072866D", "SalesOrder": "W645370", "Brand": "HONAC", "Item": "MN10CESBB", "Qty": "1", "Month": "6",  "time": "2018-06-19T16:36:22Z"}

Need to append to an existing file which has data in a similar format. 需要附加到具有类似格式数据的现有文件。 But the resulting file is getting all messed up. 但是结果文件变得一团糟。 I need append this file several times a day. 我每天需要几次附加此文件。 The code looks like: 代码如下:

csvfile1 = open('daily.csv', 'r')
jsonfile1 = open('test3.json', 'a')
fieldnames = list(raw_data.columns.values)
reader1 = csv.DictReader( csvfile1, fieldnames)


next(reader1)
jsonfile1.write('\n')
pos = next1 = 0
for row in reader1:
    pos = next1
    next1 += len(row) # compute position of beginning of next line
    json.dump(row, jsonfile1)
    jsonfile1.write('\n')
jsonfile1.truncate(pos)

The final output is not exactly the append. 最终输出不完全是追加。 It is some malformed file with incomplete json objects. 这是格式错误的文件,其中包含不完整的json对象。

Consider closing files when you're finished (or use with-as). 完成后考虑关闭文件(或使用with-as)。 Also not sure why you calculate position to truncate (on 'a' mode) at the end of appending. 也不确定为什么要在追加末尾计算要截断的位置(在“ a”模式下)。

import csv
import json

fieldnames = ("CustomerNo", "SalesOrder", "Brand", "Item", "Qty", "Month", "time")

# Handle the case when there is no newline at the end. Format a file before appending.

with open('daily.csv', 'r') as csvfile1:
    with open('test3.json', 'a') as jsonfile1:
        for row in csv.DictReader(csvfile1, fieldnames):
            json.dump(row, jsonfile1)
            jsonfile1.write('\n')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM