Created
February 8, 2016 17:25
-
-
Save natereed/bedad27affe3b0c3010b to your computer and use it in GitHub Desktop.
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
import json | |
import csv | |
# REPLACE THIS with json input | |
#input = '{"Parent": "Roy", "Children": [{"Name": "Todd"}, {"Name": "Shirley"}]}' | |
f = open("my.json", "r") | |
contents = f.read() | |
obj = json.loads(contents) | |
def flatten_object(obj, tree = []): | |
flattened_obj = {} | |
if type(obj) != dict and type(obj) != list: | |
fq_name = '.'.join(tree) | |
flattened_obj[fq_name] = obj | |
return flattened_obj | |
for index, value in enumerate(obj): | |
# For dicts, value is the key of the item in the dict, eg. {1: 'One', 2: 'Two'} yields values of 1 and 2 | |
# For lists, value is the actual item eg. [1,2,3] yields values of 1, 2, and 3 | |
#if (type(obj) == dict): | |
# value = obj[value] | |
# The fully-qualified name of the node is based on new_tree, which | |
# is a list of ancestor nodes of the current node. For dictionaries, we use the dictionary key | |
# as the name of the node, and for lists we use the index. | |
new_tree = list(tree) | |
if (type(obj) is dict): | |
new_tree.append(str(value)) | |
else: | |
new_tree.append(str(index)) | |
if type(obj) is dict: | |
# value is a dictionary key. recurse on the object referenced by value | |
flattened_obj.update(flatten_object(obj[value], new_tree)) | |
elif type(obj) is list: | |
flattened_obj.update(flatten_object(value, new_tree)) | |
return flattened_obj | |
object_map = flatten_object(obj) | |
with open("flattened.csv", "w") as output_file: | |
fieldnames = [key for key in object_map.keys()] | |
print fieldnames | |
writer = csv.DictWriter(output_file, fieldnames) | |
writer.writeheader() | |
for key in object_map.keys(): | |
row = dict() | |
row[key] = object_map[key] | |
writer.writerow(row) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment