[英]How to import data from nested JSON file to CSV?
我有一个嵌套的 json 文件,我想使用 Python 将其中的一些内容写入 csv 文件。 我已经设法选择了我想要的数据,但我不明白如何让 Python 从所有索引中写入数据。 换句话说,我一次只能从一个索引写入数据,我不明白如何选择所有索引。 我尝试使用切片,但它给了我 TypeError (列表索引必须是整数或切片等)。 你可以帮帮我吗? 谢谢!
这是到目前为止的代码(它可以工作,但它只写了 1 行,而我有 87 行):
import json
import csv
json_file = open("unique_json.json", "r", encoding="utf-8")
csv_file = open("csv_format2.csv", "w", encoding="utf-8")
data = json.load(json_file)
write = csv.writer(csv_file)
contents = [[data[0]["node"]["display_url"]],
[data[0]["node"]["edge_liked_by"]["count"]],
[data[0]["node"]["edge_media_to_comment"]["count"]],
[data[0]["node"]["taken_at_timestamp"]]]
headers = ["url", "likes", "comments", "timestamp"]
write.writerow(headers)
for i in contents:
for j in i:
print(j, end=",", file=csv_file)
json_file.close()
csv_file.close()
几件事:
with
语句来处理退出文件时关闭文件,即使有异常也是如此。writer
而不是write
。data
每个项目使用for
循环。[]
),这就是为什么里面有第二个for
循环的原因。import json
import csv
with open("unique_json.json", "r", encoding="utf-8") as json_file:
data = json.load(json_file)
with open("csv_format2.csv", "w", encoding="utf-8") as csv_file
writer = csv.writer(csv_file)
writer.writerow(["url", "likes", "comments", "timestamp"])
for row in data:
writer.writerow([
row["node"]["display_url"],
row["node"]["edge_liked_by"]["count"],
row["node"]["edge_media_to_comment"]["count"],
row["node"]["taken_at_timestamp"],
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.