python - 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 文件中得到错误,字典和“预期文件结尾”之间没有逗号。有一个更好的方法吗?
解决方案
您需要将其作为列表转储,而不是作为单个条目:
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)
推荐阅读
- php - 此登录代码的 mysqli 等效项是什么?
- python - 如何解决在 Mac 上运行的 Python 中的导入错误?
- python-3.x - sqlite3 错误:您没有为绑定 1 提供值
- uwp - 媒体基础库中的 UWP AAC 编码,未注册类
- php - Bootstrap手风琴在选择另一个后不会折叠
- c# - C# 无法避免嵌套的 try-catch
- docker - 在 Docker 中为 Ubuntu 16.04 运行 Systemd,对于 Ubuntu 18.04 它可以工作
- javascript - 提交表单时通过 JS 验证号码
- mysql - 插入时出错
- angular - 如何在 Ionic 无限滚动中从 Wordpress API 输出累积列表