0

I'm trying to write a simple JSON to CSV converter in Python for Kiva. The JSON file I am working with looks like this:

{"header":{"total":412045,"page":1,"date":"2012-04-11T06:16:43Z","page_size":500},"loans":[{"id":84,"name":"Justine","description":{"languages":["en"], REST OF DATA

The problem is, when I use json.load, I only get the strings "header" and "loans" in data, but not the actual information such as id, name, description, etc. How can I skip over everything until the [? I have a lot of files to process, so I can't manually delete the beginning in each one. My current code is:

import csv
import json

fp = csv.writer(open("test.csv","wb+"))

f = open("loans/1.json")
data = json.load(f)
f.close()

for item in data:
    fp.writerow([item["name"]] + [item["posted_date"]] + OTHER STUFF)

2 Answers 2

4

Instead of

for item in data:

use

for item in data['loans']:

The header is stored in data['header'] and data itself is a dictionary, so you'll have to key into it in order to access the data.

Sign up to request clarification or add additional context in comments.

1 Comment

Ohhh, I see. Thank you. I was wondering if there was a way to reference the information in header and loans within my code. Newbie Python user, so the dictionaries still confuse me a bit.
0

data is a dictionary, so for item in data iterates the keys.

You probably want for loan in data['loans']:

2 Comments

Ah, okay. So if I wanted to iterate through all the data in all the keys, I would nest a loop like for keys in data for item in data[keys] DO STUFF
You can do that, but in python if you are iterating keys+values you usually just iterate both at the same time instead of using another for-loop: for key,value in data.items(): DO STUFF

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.