I'm trying to convert JSON data into CSV format so I can import it into LibreCalc. I've found a pretty simple Python script that almost does what I'm looking for, but it doesn't quite work properly.
This is the script I've made, taken from snippets of code in the guide link. EDIT: I can't add the link as stack overflow thinks its spam.
import json
import csv
#read file
with open('test.json', 'r') as jsonfile:
data=jsonfile.read()
# parse file
jsonobj = json.loads(data)
def jsontocsv(input_json, output_path):
keylist = []
for key in jsonobj[0]:
keylist.append(key)
f = csv.writer(open(output_path, "w"))
f.writerow(keylist)
for record in jsonobj:
currentrecord = []
for key in keylist:
currentrecord.append(record[key])
f.writerow(currentrecord)
jsontocsv(jsonobj,'test.csv')
And this is the test JSON data, also taken from the links example.
[{
"Name" : "Bob",
"City" : "San Diego",
"State" : "CA"
},
{
"Name" : "Sue",
"City" : "San Francisco",
"State" : "CA"
},
{
"Name" : "Ted",
"City" : "New York",
"State" : "NY"
},
{
"Name" : "Joe",
"City" : "Miami",
"State" : "FL"
}]
When I run the script, instead of getting a CSV file that looks like this:
Name,City,State
Bob,San Diego,CA
Sue,San Francisco,CA
Ted,New York,NY
Joe,Miami,FL
I get this...
City,State,Name
San Diego
San Diego,CA
San Diego,CA,Bob
San Francisco
San Francisco,CA
San Francisco,CA,Sue
New York
New York,NY
New York,NY,Ted
Miami
Miami,FL
Miami,FL,Joe
I'm literally copying this guys code and following his example, so I'm not sure what I'm doing wrong. I've tried playing with it a bit and changing the indenting etc, but nothing seems to work. I'm sure it's something ridiculously simple, and no doubt something I've messed up, but I can't figure it out.
Using my own JSON files with the actual data I want to convert has the same effect.
Any help with this would be appreciated.
Thank you.
