首页 > 解决方案 > for循环字典写入json

问题描述

我有一个从 API 中提取信息的脚本。API 是一个用于发布招聘信息的数据库,我以 json 格式接收信息。

然后我给不同的标题、名称、日期一个变量。变量由 for 循环更新并一个接一个地打印,所以我最终会得到这样的帖子:

ID: 234523
jobtitle
company
deadline
link

ID: 5454554
jobtitle
company
deadline
link

etc.

我现在想要的是将它输出到一个 json 文件,以便我以后可以比较 ID 并将新的帖子添加到文件中。我目前遇到的问题是,在database.json像这样输出文件后,文件中的格式已关闭:

for i in jobs:
    employername = i['employer']
    emp_type = i['employment_type']
    fulltime = i['duration']
    jobtitle = i['headline']
    etc.


    output = {
        'ID': job_id, 
        'Title': jobtitle, 
        'Employer' : company, 
        'Employment type' : emptype, 
        'Fulltime' : tid, 
        'Deadline' : deadline, 
        'Link' : webpage
    }
    with open('pbdb.json', 'a+') as job_data_file:
        json.dump(output, job_data_file, indent=4,)

输出将类似于:

{
    "ID": "23961983",
    "Title": "Test",
    "Employer": "comp",
    "Employment type": "regular",
    "Fulltime": "fulltime",
    "Deadline": "2020-09-06",
    "Link": "https://"
}{
    "ID": "23960352",
    "Title": "a job",
    "Employer": "comp2",
    "Employment type": "regular",
    "Fulltime": "4 months",
    "Deadline": "2020-03-27",
    "Link": "https://"
}

我会在 json 文件中得到错误,字典和“预期文件结尾”之间没有逗号。有一个更好的方法吗?

标签: pythonjsonpython-3.xdictionary

解决方案


您需要将其作为列表转储,而不是作为单个条目:

output = []
for i in jobs:
    ...

    output.append({
        'ID': job_id, 
        'Title': jobtitle, 
        'Employer' : company, 
        'Employment type' : emptype, 
        'Fulltime' : tid, 
        'Deadline' : deadline, 
        'Link' : webpage
    })

with open('pbdb.json', 'w') as job_data_file:
    json.dump(output, job_data_file)

使其附加到 json 文件:

output = json.load(open("pbdb.json"))

如果文件为空则中断,解决方法:

import os

check_empty = os.stat('pbdb.json').st_size
if check_empty == 0:
    with open('pbdb.json', 'w') as f:
        f.write('[\n]')    # Writes '[' then linebreaks with '\n' and writes ']'
output = json.load(open("pbdb.json"))

for i in jobs:
    output.append({
        'ID': job_id, 
        'Title': jobtitle, 
        'Employer' : company, 
        'Employment type' : emptype, 
        'Fulltime' : tid, 
        'Deadline' : deadline, 
        'Link' : webpage
    })

with open('pbdb.json', 'w') as job_data_file:
    json.dump(output, job_data_file)

推荐阅读