I have a nested json file and I want to write some of its contents into a csv file using Python. I have managed to select the data I want, but I don't understand how to ask Python to write data from all the indexes. In other words, I can only write data from one index at a time, I don't understand how to select all indexes. I tried with a slice but it gives me TypeError (list indices must be integers or slices, etc.). Could you help me? Thanks!
This is the code so far (it works, but it just writes 1 line and I have 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()
for row in contents: write.writerow(row)? Let me know if this doesn't make sense. :)