天天看点

python合并json_组合两个json字典python

鉴于OP的问题有一个包含JSON内容的文件,这个答案可能更好:import json

import ast

myFile = 'myFile.json'

jsonString = lastLineofFile(myfile)

d = ast.literal_eval(jsonString) # from file

d.update(dict)

with open(myFile, 'a') as f:

json.dump(d, f)

此外,由于这是增量的,因此可以通过以下有效的帮助函数获取文件的最后一行:# Read the last line of a file. Return 0 if not read in 'timeout' number of seconds

def lastLineOfFile(fileName, timeout = 1):

elapsed_time = 0

offset = 0

line = ''

start_time = time.time()

with open(fileName) as f:

while True and elapsed_time < timeout:

offset -= 1

f.seek(offset, 2)

nextline = f.next()

if nextline == '\n' and line.strip():

return line

else:

line = nextline

elapsed_time = time.time() - start_time

if elapsed_time >= timeout:

return None