I have a dict like this:
sample = {'ObjectInterpolator': 1629, 'PointInterpolator': 1675, 'RectangleInterpolator': 2042} I can't figure out how to dump the dict to a JSON file as showed below:
{ "name": "interpolator", "children": [ {"name": "ObjectInterpolator", "size": 1629}, {"name": "PointInterpolator", "size": 1675}, {"name": "RectangleInterpolator", "size": 2042} ] } Is there a pythonic way to do this?
You may guess that I want to generate a d3 treemap.
You can convert a dictionary to a JSON string using the json. dumps() method. The process of encoding the JSON is usually called serialization. That term refers to transforming data into a series of bytes (hence serial) stored or transmitted across the network.
To Convert dictionary to JSON you can use the json. dumps() which converts a dictionary to str object, not a json(dict) object! so you have to load your str into a dict to use it by using json.
dumps() method: This method is used to convert the dictionary object into JSON data for parsing or reading and it is slower than dump() method.
import json with 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, j f.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/
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