holys
holys

Reputation: 14769

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.

Upvotes: 477

Views: 820829

Answers (8)

Luss Sh
Luss Sh

Reputation: 41

my_dict = {'one':1,'two':2}    
with open('your_filename', 'w') as fp:
  json.dump(my_dict, fp, indent=4, ensure_ascii=False)
  fp.close()

Upvotes: 0

davidvandebunte
davidvandebunte

Reputation: 1486

If you're using Path:

Path('result.json').write_text(json.dumps(sample, indent=4) + '\n')

Upvotes: 8

holys
holys

Reputation: 14769

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/

Upvotes: 59

mgilson
mgilson

Reputation: 309831

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

Upvotes: 29

als0052
als0052

Reputation: 446

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.

Upvotes: 26

jmhostalet
jmhostalet

Reputation: 4639

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)

Upvotes: 18

moobi
moobi

Reputation: 8449

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!

Upvotes: 801

John La Rooy
John La Rooy

Reputation: 304137

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
    }
]

Upvotes: 17

Related Questions