I have a defaultdict(list)
and I used simplejson.dumps(my_defaultdict)
in order to output the defaultdict
into a JSON format. I am using the HTML code for dendogram from http://bl.ocks.org/mbostock/4063570 but I am trying to make my defaultdict
information into the format of the JSON file the author is using. This JSON file is named: /mbostock/raw/4063550/flare.JSON
and it's found in this link: http://bl.ocks.org/mbostock/raw/4063550/flare.json.
So here is my defaultdict data:
my_defaultdict = {5: ['child10'], 45: ['child92', 'child45'], 33:['child38']}
json_data = simplejson.dumps(my_defaultdict)
so my current json_data looks like this:
{
"5": [
"child10"
],
"45": [
"child92",
"child45"
],
"33": [
"child38"
]
}
So in my understanding the numbers would be the corresponding "name":"5" and then my JSON format file would also have the children as "children". As what it is right now, my JSON format output doesn't run in the HTML code of the dendogram.
The expected outcome would be like this:
{
"name": "flare",
"children": [
{
"name": "5",
"children": [
{
"name": "child10", "size": 5000},
]
{
"name": "45",
"children": [
{"name": "child92", "size": 3501},
{"name": "child45", "size": 3567},
]
},
{
"name": "33",
"children": [
{"name": "child38", "size": 8044}
]
}
}
Edit:
The answer of @martineau works, but it's not exactly what I want. I start with a defaultdict(list)
and the desired output, as above should have the "children" as a list of dict
s whereas with martineau kind answer, the "children" it's just a list. If anybody can add something to that to make it work it would be great. Don't worry about the "size" variable, this can be ignored for now.
You need to make a new dictionary from your defaultdict. The children in your example code is just a list of strings, so I don't know where the "size" of each one comes from so just changed it into a list of dicts
(which don't have a an entry for a "size" key).
from collections import defaultdict
#import simplejson as json
import json # using stdlib module instead
my_defaultdict = defaultdict(list, { 5: ['child10'],
45: ['child92', 'child45'],
33: ['child38']})
my_dict = {'name': 'flare',
'children': [{'name': k,
'children': [{'name': child} for child in v]}
for k, v in my_defaultdict.items()]}
json_data = json.dumps(my_dict, indent=2)
print(json_data)
Output:
{
"name": "flare",
"children": [
{
"name": 33,
"children": [
{
"name": "child38"
}
]
},
{
"name": 5,
"children": [
{
"name": "child10"
}
]
},
{
"name": 45,
"children": [
{
"name": "child92"
},
{
"name": "child45"
}
]
}
]
}
I solved by using this: How to convert defaultdict to dict?
For future people that may search for it. I achieved by transforming the defaultdict
into a commom dictionary just calling:
b = defaultdict(dict)
a = dict(b)
Then the JSON could recognize this structure.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With