【发布时间】:2019-11-27 20:11:35
【问题描述】:
我正在尝试编写一个采用 python 脚本并将其转换为 json 的代码。所以我基本上是在抓取文件并将所需的值添加到我在下面给出的字典中。我需要将多个任务写入字典。
对于 new_data 中的行:
if re.search(r'task_id=',line ):
#write to dic['tasks'][0]['task_id']
(here there are multiple matches for task_id, so I have to iterate through the list and should be able to write to task_id)
我已经试过了:
dic['tasks'][0]['task_id'] = line.split(":")[1]
但它会抛出list out of index error。我不明白为什么会抛出这个错误。
dic = {
"tasks": [{
"task_id": "1",
"description": "Short Description.",
"bitbucket_link": "",
"can_restart": True,
"cluster_size": "",
"notes": ""
}]
}
虽然预期的输出应该是:
dic = {
"tasks": [{
"task_id": "1",
"description": "Short Description.",
"bitbucket_link": "",
"can_restart": True,
"cluster_size": "",
"notes": ""
}, {
"task_id": "2",
"description": "Short Description.",
"bitbucket_link": "",
"can_restart": True,
"cluster_size": "",
"notes": ""
}]
}
【问题讨论】:
-
您能否在
developers键中添加内容?在您给出的示例中,我只看到tasks键里面有什么!你明白我在问什么吗? -
该错误表示
line中没有:。line是什么? -
请添加源字典的sn-p。没有它,我们无法帮助您。另外,您不需要在这里寻求帮助,我们已经知道了。看看我对您的代码所做的编辑,以了解如何更好地格式化代码 sn-ps。
-
for line in new_data: if re.search(r'task_id=',line ): #write to dic['tasks'][0]['task_id'] (这里有多个匹配对于task_id,所以我必须遍历列表并且应该能够写入task_id)
标签: python json dictionary nested