json到csv编写嵌套的dict内容

时间:2016-02-15 09:26:21

标签: python json csv

我正在尝试将一些json结果内容写入csv,json内容为 - https://gist.github.com/anonymous/6cf68a53898b8a7c1324

这是我将json写入csv的代码

for item in result:
    partial_data = json.loads(item['result'])
    for rec in partial_data['results']:
        with open("data.csv", "w") as file:
            csv_file = csv.writer(file)
            #csv_file.writerow(rec['general_article'],rec['author_name'],rec['infographic'],rec['video'],rec['pinterest_shares'],rec['id'],rec['num_words'],rec['linkedin_shares'],rec['title'],rec['domain_name'],rec['subdomain'],rec['thumbnail'],rec['display_title'],rec['total_shares_with_pinterest'],rec['total_shares'],rec['twitter_shares'],rec['twitter_user_id'],rec['url'],rec['article_types'],rec['google_plus_shares'],rec['published_date'],rec['og_url'])
            csv_file.writerow(rec)

我尝试了不同的方式,上面的代码给出了

*** Error: sequence expected

如果我单独写所有值

TypeError: 'writerow() takes exactly one argument (22 given)'

这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

csv.writerow()方法不接受词典格式的数据,但采用 list 格式。

您可以做的是将词典转换为列表列表,然后您可以使用csv.writerows()方法一次性插入所有行

像这样:

for item in result:
    partial_data = json.loads(item['result'])
    outer_list = []
    for rec in partial_data['results']:
        inner_list = []
        for key, value in rec:
            inner_list.append(...) # values from the dictionary
        outer_list.append(inner_list)

with open("data.csv", "w", newline='') as file:
    csv_file = csv.writer(file, delimiter=',')
    csv_file.writerow(['published_date', 'linkedin_shares', ... , 'display_title']) # Column label names
    csv_file.writerows(outer_list)