This repository has been archived by the owner on Mar 24, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #265 from alphagov/json-to-csv-convert-script
Script to convert our JSON to CSV
- Loading branch information
Showing
1 changed file
with
39 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
#!/usr/bin/env python | ||
# encoding: utf-8 | ||
|
||
""" | ||
Rough and ready conversion script to turn our JSON output into CSV. | ||
Note that this only works on "flat" data like, such as what you get from a raw | ||
query in backdrop. It can't handle nesting, like when you've used a group_by | ||
query. | ||
""" | ||
|
||
import json | ||
import csv | ||
import sys | ||
|
||
|
||
def main(filename): | ||
with open(filename, 'r') as f, open('out.csv', 'w') as g: | ||
data = json.loads(f.read()) | ||
|
||
field_names = set() | ||
for row in data['data']: | ||
field_names.update(set(row.keys())) | ||
|
||
csv_writer = csv.DictWriter( | ||
g, | ||
fieldnames=sorted(field_names), | ||
delimiter=',') | ||
csv_writer.writeheader() | ||
|
||
for row in data['data']: | ||
csv_writer.writerow(row) | ||
|
||
if __name__ == '__main__': | ||
if len(sys.argv) == 2: | ||
main(sys.argv[1]) | ||
else: | ||
print("Usage: {} <file.json>".format(sys.argv[0])) | ||
sys.exit(2) |