377

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
  • 18,131
  • 10
  • 32
  • 49
holys
  • 12,423
  • 13
  • 42
  • 50

7 Answers7

635
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
  • 6,789
  • 2
  • 17
  • 29
54

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/

holys
  • 12,423
  • 13
  • 42
  • 50
  • 28
    `print(j, file=f)` in Python 3.6 (instead of `print >> f, j`) – mjkrause Dec 29 '17 at 15:06
  • 2
    `print(j, file=f)` didn't work for me,I didn't need to do the J part as well. `d = {'a':1, 'b':2} print(d, file=open('sample.json', 'wt'))` worked. – H S Rathore May 23 '20 at 07:08
  • You can also use `indent` to create formatted dump: `json.dump(content, file, indent=4)` – deshu Feb 10 '22 at 15:37
26
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 ...

mgilson
  • 283,004
  • 58
  • 591
  • 667
18

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
  • 281,034
  • 50
  • 354
  • 495
15

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
  • 3,961
  • 4
  • 36
  • 42
  • 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
9

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
  • 159
  • 2
  • 11
3

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,046
  • 13
  • 22