【问题标题】:for loop dict written to jsonfor循环字典写入json
【发布时间】:2025-11-27 15:05:02
【问题描述】:

我有一个从 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 文件中得到错误,字典和“预期文件结尾”之间没有逗号。有没有更好的方法来做到这一点?

【问题讨论】:

    标签: python json python-3.x dictionary


    【解决方案1】:

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

    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)
    

    【讨论】:

    • 哦...愚蠢的我!那解决了!非常感谢你! :) 编辑:有点..第二次运行脚本会破坏它并再次创建“行尾预期错误”我猜是因为它没有附加在“[]”内
    • 对。为此,请将第一行更改为 outputs = json.load(open("pbdb.json"))。如果你这样做了,别忘了写模式w而不是a+
    • @Derpa - 看起来不错,注意检查文件是否存在的更简单方法是if os.path.exists("pbdb.json")
    • 我要做的只是检查文件是否为空,如果是,则添加 [],因为如果文件为空,json.load 会中断,现在我只需要弄清楚如何在将信息添加到json文件之前检查信息是否已经存在<.>