A simple recursive solution:
data = {"outfit":{"shirt":"red","pants":{"jeans":"blue","trousers":"khaki"}}}
import json
from collections import OrderedDict
def node(name, children):
n = OrderedDict()
n['id'] = 'node' + name.capitalize()
n['name'] = name
n['data'] = {}
n['children'] = children
return n
def convert(d):
if type(d) == dict:
return [node(k, convert(v)) for k, v in d.items()]
else:
return [node(d, [])]
print(json.dumps(convert(data), indent=True))
note that convert
returns a list
, not a dict
, as data
could also have more then one key then just 'outfit'
.
output:
[ { "id": "nodeOutfit", "name": "outfit", "data": {}, "children": [ { "id": "nodeShirt", "name": "shirt", "data": {}, "children": [ { "id": "nodeRed", "name": "red", "data": {}, "children": [] } ] }, { "id": "nodePants", "name": "pants", "data": {}, "children": [ { "id": "nodeJeans", "name": "jeans", "data": {}, "children": [ { "id": "nodeBlue", "name": "blue", "data": {}, "children": [] } ] }, { "id": "nodeTrousers", "name": "trousers", "data": {}, "children": [ { "id": "nodeKhaki", "name": "khaki", "data": {}, "children": [] } ] } ] } ] } ]