【发布时间】:2017-05-26 02:37:41
【问题描述】:
我正在尝试解析大量数据以自动创建此报告。除了 JSON 数据每个项目都有一个标签列表外,我大部分时间都在工作。它们嵌套在每个“任务项”中。
我希望 csv 看起来像这样
Name,Title,Description,Priority,Tag1, Tag2, Tag3, Tag4
下面的代码可以工作,除了因为 json 数据中的标签像嵌套一样
tags: [
{
id: 56131,
name: "NotNeeded",
color: "#a6a6a6"
},
{
id: 60598,
name: "Other",
color: "#f47fbe"
},
{
id: 60493,
name: "Test",
color: "#2f8de4"
}
我只想要标签,而不想要其他东西。我希望在每一行的末尾添加每个标签。有些有三个标签,有些有一个等等。我只是想让它们现在写,但是使用这段代码,它们都打印在第 1 列的新行上。
除此之外,我还想在其中构建一个 if 语句来确定它位于哪个标签标题下...例如 if name = "Other" put under header Tag3
with open('test.csv', 'w', newline='') as csvfile:
csvwriter = csv.writer(csvfile, lineterminator='\n')
csvwriter.writerow(["Name", "Title", "Description", "priority", "tags"])
for each in jdata['todo-items']:
csvwriter.writerow([(each["todo-list-name"]),
(each["content"]),
(each["description"]),
(each["priority"])])
for tags in each['tags']:
csvwriter.writerow([(tags["name"])])
编辑: 到目前为止,这按我想要的方式工作(除了标签在输出中周围有 ['Tag'] 。
with open('test.csv', 'w', newline='') as csvfile:
csvwriter = csv.writer(csvfile, lineterminator='\n')
csvwriter.writerow(["Name", "Title", "Description", "priority", "tags"])
for each in jdata['todo-items']:
write_list = [(each["todo-list-name"]),
(each["content"]),
(each["description"]),
(each["priority"])]
for tags in each['tags']:
write_list.append([(tags["name"])])
csvwriter.writerow(write_list)
【问题讨论】:
-
您希望标签是单独的列,还是在同一列中?
-
分开我认为最好,这样我以后可以在excel中应用过滤器。因此我希望他们匹配过滤器。如果名称是其他所有其他人应该在同一列。因为如果一个有 2 个标签,那么它可能有 NotNeeded、Other 和下一个只有一个标签,Other。如果没有 IF 语句,Other 将进入上一个 NotNeeded 下的第一列。
-
@CarverStone 您现在可以接受自己的答案
标签: python json python-3.x csv