stardamore
stardamore

Reputation: 150

Saving JSON result into CSV

So I'm pulling data in JSON from an API which has dicts and multiple lists in it. The data I pull gets parsed and printed correctly, it's saving it in the CSV that's a problem.

r=requests.get(url,headers=header)
result=r.json()
for log in result['logs']:
    print('Driver ID: ', log['log']['driver']['username'])
    print('First Name: ', log['log']['driver']['first_name'])
    print('Last Name: ', log['log']['driver']['last_name'])
    for event in log['log']['events']:
        print('ID: ', event['event']['id'])
        print('Start Time: ', event['event']['start_time'])
        print('Type: ', event['event']['type'])
        print('Location: ', event['event']['location'])
with open ('data.csv','w') as csvfile:
    f=csv.writer(csvfile)
    f.writerow(['username','first_name'])
    for elem in result['logs']:
        f.writerow([elem['log']['driver']['username']],elem[log['log']['driver']['first_name']]])

I'm only starting on adding the username and first_name into the CSV but I keep getting an error saying:

KeyError: 'Robert'

It's important to note that 'Robert' is not the username, it's the first name. Also, it's the last result in the JSON response, shouldn't the logic start from the top? Any ideas on how to fix it?

This is the API I'm fetching the data from, the endpoint is /logs: https://developer.keeptruckin.com/reference#get-logs

Upvotes: 0

Views: 42

Answers (2)

Alcamtar
Alcamtar

Reputation: 1582

You are dereferencing elem[log['log']] instead of elem['log']

- f.writerow([elem['log']['driver']['username']],elem[log['log']['driver']['first_name']]])
+ f.writerow([elem['log']['driver']['username'],elem['log']['driver']['first_name']])

Upvotes: 1

Chris
Chris

Reputation: 1697

I think you meant this:

-         f.writerow([elem['log']['driver']['username']],elem[log['log']['driver']['first_name']])
+         f.writerow([elem['log']['driver']['username'],elem[log['log']['driver']['first_name']]])

Upvotes: 1

Related Questions