Search code examples
pythonjsondictionarypython-requestsexport-to-csv

How to convert python-request JSON results to csv?


I am trying to get my list of contacts from my WIX website using their API endpoint url and the requests module in python. I am totally stuck. Here's my code so far:

import requests

auth_key = "my auth key"
r = requests.get("https://www.wixapis.com/crm/v1/contacts", headers={"Authorization": auth_key})
print(r.status_code)
dict = r.json()
contacts_list = dict["contacts"]

for i in contacts_list:
    for key in i:
        print(key, ':', i[key])

Here is what I get:

200
id : long id string 1
emails : [{'tag': 'UNTAGGED', 'email': 'sampleemail1@yahoo.com'}]
phones : []
addresses : [{'tag': 'UNTAGGED', 'countryCode': 'US'}]
metadata : {'createdAt': '2020-07-08T22:41:07.135Z', 'updatedAt': '2020-07-08T22:42:19.327Z'}
source : {'sourceType': 'SITE_MEMBERS'}
id : long id string 2
emails : [{'tag': 'UNTAGGED', 'email': 'sampleemail2@yahoo.com'}]
phones : []
addresses : []
metadata : {'createdAt': '2020-07-03T00:51:21.127Z', 'updatedAt': '2020-07-04T03:26:16.370Z'}
source : {'sourceType': 'SITE_MEMBERS'}

Process finished with exit code 0

Each line is a string. I need each row of the csv to be a new contact (There are two sample contacts). The columns should be the keys. I plan to use the csv module to writerow(Fields), where fields is a list of string (keys) such as Fields = [id, emails, phones, addresses, metadata, source]

All I really need is the emails in a single column of a csv though. Is there a way to maybe just get the email for each contact?


Solution

  • A CSV file with one column is basically just a text file with one item per line, but you can use the csv module to do it if you really want, as shown below.

    I commented-out the 'python-requests' stuff and used some sample input for testing.

    test_data = {
        "contacts": [
            {
                "id": "long id string 1",
                "emails": [
                    {
                        "tag": "UNTAGGED",
                        "email": "sampleemail1@yahoo.com"
                    }
                ],
                "phones": [],
                "addresses": [
                    {
                        "tag": "UNTAGGED",
                        "countryCode": "US"
                    }
                ],
                "metadata": {
                    "createdAt": "2020-07-08T22:41:07.135Z",
                    "updatedAt": "2020-07-08T22:42:19.327Z"
                },
                "source": {
                    "sourceType": "SITE_MEMBERS"
                }
            },
            {
                "id": "long id string 2",
                "emails": [
                    {
                        "tag": "UNTAGGED",
                        "email": "sampleemail2@yahoo.com"
                    }
                ],
                "phones": [],
                "addresses": [],
                "metadata": {
                    "createdAt": "2020-07-03T00:51:21.127Z",
                    "updatedAt": "2020-07-04T03:26:16.370Z"
                },
                "source": {
                    "sourceType": "SITE_MEMBERS"
                }
            }
        ]
    }
    
    
    import csv
    import json
    import requests
    
    
    auth_key = "my auth key"
    output_filename = 'whatever.csv'
    
    #r = requests.get("https://www.wixapis.com/crm/v1/contacts", headers={"Authorization": auth_key})
    #print(r.status_code)
    #json_obj = r.json()
    
    json_obj = test_data  # FOR TESTING PURPOSES
    contacts_list = json_obj["contacts"]
    
    with open(output_filename, 'w', newline='') as outp:
        writer = csv.writer(outp)
        writer.writerow(['email'])  # Write csv header.
    
        for contact in contacts_list:
            email = contact['emails'][0]['email']  # Get the first one.
            writer.writerow([email])
    
    print('email csv file written')
    

    Contents of whatever.csv file afterwards:

    email
    sampleemail1@yahoo.com
    sampleemail2@yahoo.com