简体   繁体   English

将所有值写入一行csv.DictWriter

[英]Write all values in one line csv.DictWriter

I'm having trouble to generate a well formatted CSV file out of some data i fetched from the leadfeeder API. 我无法从从Leadfeeder API获取的某些数据中生成格式正确的CSV文件。 In the csv file that is currently being created, not all values are in one row, id and leads are one column higher then the rest. 在当前正在创建的csv文件中,并非所有值都在一行中,id和Leads比其他值高一列。 Like here: 像这儿:

CSV Output CSV输出

I later also like to load another json file and use it to map some values over the id and then put also the visits per lead into my csv file. 后来我也想加载另一个json文件,并使用它在id上映射一些值,然后将每条线索的访问量也放入我的csv文件中。

Do you also have some advice for this? 您对此有什么建议吗?

This is my code so far: 到目前为止,这是我的代码:

import json
import csv

csv_columns = ['name', 'industry', 'website_url', 'status', 'crm_lead_id', 'crm_organization_id', 'employee_count', 'id', 'type' ]

with open('data.json', 'r') as d:    
    d = json.load(d)

csv_file = 'lead_daten.csv'

try:
    with open('leads.csv', 'w', newline='') as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=csv_columns, extrasaction='ignore')
        writer.writeheader()
        for item in d['data']:
            writer.writerow(item)
            writer.writerow(item['attributes'])

except IOError:
    print("I/O error")

My json data has the following structure: I need also some of the nested values like the id in relationships! 我的json数据具有以下结构: 我还需要一些嵌套值,例如关系中的id!

{
    "data": [
        {
            "attributes": {
                "crm_lead_id": null, 
                "crm_organization_id": null, 
                "employee_count": 5000, 
                "facebook_url": null, 
                "first_visit_date": "2019-01-31", 
                "industry": "Furniture", 
                "last_visit_date": "2019-01-31", 
                "linkedin_url": null, 
                "name": "Example Inc", 
                "phone": null, 
                "status": "new", 
                "twitter_handle": "example", 
                "website_url": "http://www.example.com"
            }, 
            "id": "s7ybF6VxqhQqVM1m1BCnZT_8SRo9XnuoxSUP5ChvERZS9", 
            "relationships": {
                "location": {
                    "data": {
                        "id": "8SRo9XnuoxSUP5ChvERZS9", 
                        "type": "locations"
                    }
                }
            }, 
            "type": "leads"
        }, 
        {
            "attributes": {
                "crm_lead_id": null, 

When you write to a csv, you must write one full row at a time. 写入csv时,必须一次写入一整行。 You current code writes one row with only id and type, and then a different row with the other fields. 您当前的代码只用id和type写入一行,然后用其他字段写入另一行。

The correct way is to first fully build a dictionary containing all the fields and only then write it in one single operation. 正确的方法是首先完全构建一个包含所有字段的字典,然后再执行一次操作。 Code could be: 代码可以是:

    ...
    writer.writeheader()
    for item in d['data']:
        item.update(item["attributes"])
        writer.writerow(item)
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM