439

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.

Syscall
  • 19,327
  • 10
  • 37
  • 52
holys
  • 13,869
  • 15
  • 45
  • 50

7 Answers7

741
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!

moobi
  • 7,849
  • 2
  • 18
  • 29
57

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)
with open('sample.json', 'w') as f:
    print >> f, j

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/

Andreu Gimenez
  • 413
  • 5
  • 9
holys
  • 13,869
  • 15
  • 45
  • 50
29
d = {"name":"interpolator",
     "children":[{'name':key,"size":value} for key,value in sample.items()]}
json_string = json.dumps(d)

Since python 3.7 the ordering of dicts is retained https://docs.python.org/3.8/library/stdtypes.html#mapping-types-dict

Dictionaries preserve insertion order. Note that updating a key does not affect the order. Keys added after deletion are inserted at the end

baxx
  • 3,956
  • 6
  • 37
  • 75
mgilson
  • 300,191
  • 65
  • 633
  • 696
20

Also wanted to add this (Python 3.7)

import json

with open("dict_to_json_textfile.txt", 'w') as fout:
    json_dumps_str = json.dumps(a_dictionary, indent=4)
    print(json_dumps_str, file=fout)

Update (11-04-2021): So the reason I added this example is because sometimes you can use the print() function to write to files, and this also shows how to use the indentation (unindented stuff is evil!!). However I have recently started learning about threading and some of my research has shown that the print() statement is not always thread-safe. So if you need threading you might want to be careful with this one.

als0052
  • 388
  • 3
  • 13
17

This should give you a start

>>> import json
>>> print json.dumps([{'name': k, 'size': v} for k,v in sample.items()], indent=4)
[
    {
        "name": "PointInterpolator",
        "size": 1675
    },
    {
        "name": "ObjectInterpolator",
        "size": 1629
    },
    {
        "name": "RectangleInterpolator",
        "size": 2042
    }
]
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
16

with pretty-print format:

import json

with open(path_to_file, 'w') as file:
    json_string = json.dumps(sample, default=lambda o: o.__dict__, sort_keys=True, indent=2)
    file.write(json_string)
jmhostalet
  • 4,399
  • 4
  • 38
  • 47
  • 6
    you can supply all those parameters to `dump(sample, file, ...)` too. The extra step of writing to a string is not needed. `dump` internally writes in chunks. This could be more efficient than to compile a (possibly huge) string first. – Adrian W Jul 02 '20 at 10:46
5

If you're using Path:

example_path = Path('/tmp/test.json')
example_dict = {'x': 24, 'y': 25}
json_str = json.dumps(example_dict, indent=4) + '\n'
example_path.write_text(json_str, encoding='utf-8')
davidvandebunte
  • 1,286
  • 18
  • 25