Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dump a dict to a JSON file?

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.

like image 638
holys Avatar asked Jun 11 '13 12:06

holys


People also ask

How do I dump a dictionary into a JSON file?

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.

Can dictionary be converted to JSON?

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.

Which method is used to convert a dictionary to JSON string?

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.


2 Answers

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!

like image 144
moobi Avatar answered Oct 02 '22 18:10

moobi


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/

like image 36
holys Avatar answered Oct 02 '22 16:10

holys