我有file.json
包含
{"list" : [
]}
我有这个dict
lead = {'title': i.css('article>.sales-info>h1::text').extract_first(),
'address': i.css('article>.primary-info>.contact>h2::text').extract_first(),
'phone': i.css('article>.primary-info>.contact>.phone::text').extract_first(),
'time': i.css('article>.primary-info>.contact>.time-info>div:nth-child(2)::text').extract_first(),
'website': i.css('.business-card-footer>.website-link::attr(href)').extract_first(),
'email': i.css('.business-card-footer>.email-business::attr(href)').extract_first(),
'portfolio_item': ''}
我需要将此dict
附加到json
列表中。
我尝试了基本的文件写入方式
with open('leads.json', 'a') as f:
f.write(json.dumps(item))
f.close()
不知道如何将其附加到json
列表中
答案 0 :(得分:1)
我认为这可能对您有用:
编辑:忘记添加write_json()
函数
def write_json(path, data, indent=4):
with open(path, 'w') as file:
json.dump(data, file, indent=indent)
def append_json(path, data, key=None):
if not os.path.exists(path):
write_json(path, data)
else:
with open(path) as file:
# load a dict of the json data
json_data = json.load(file)
# key should be a list of objects so you can __add__ them
if key is None:
json_data += data
else:
json_data[key] += data
write_json(path, json_data)
appen_json('./leads.json', [lead], 'list') # you need to pass in a list, not just dict
这种书写方式要求您传递列表而不是字典,但这是一个优势,因为您可以传递多个项目以附加而不是一次添加
如果导演中不存在新文件,将写入一个新文件;如果存在新文件,则追加一个新文件