How to dump a dict to a JSON file?
import jsonwith open('result.json', 'w') as fp: json.dump(sample, fp)
This is an easier way to do it.
In the second line of code the file result.json
gets created and opened as the variable fp
.
In the third line your dict sample
gets written into the result.json
!
Combine the answer of @mgilson and @gnibbler, I found what I need was this:
d = {"name":"interpolator", "children":[{'name':key,"size":value} for key,value in sample.items()]}j = json.dumps(d, indent=4)f = open('sample.json', 'w')print >> f, jf.close()
It this way, I got a pretty-print json file.The tricks print >> f, j
is found from here: http://www.anthonydebarros.com/2012/03/11/generate-json-from-sql-using-python/
d = {"name":"interpolator", "children":[{'name':key,"size":value} for key,value in sample.items()]}json_string = json.dumps(d)
Of course, it's unlikely that the order will be exactly preserved ... But that's just the nature of dictionaries ...