ChatGPT解决这个技术问题 Extra ChatGPT

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.

is it possible for you to accept one of the answers?

m
moobi
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!


@Danish Don't know. Unless there is a question already on SO about your problem, you should create a new question describing your issue. (btw, i m simply an editor of those posts)
Tip : If you don't want to write to a file, and only see the output, try redirecting it to stdout: json.dump('SomeText', sys.stdout)
@Dan-ish Have you tried json.dump(sample, fp, sort_keys=False ) ? Assuming I understand what you mean.
Good thing to remember here is that unless you use an OrderedDict (python >2.7) there is no guarantee that keys are ordered in any particular manner
@Vijay, the function is called dump (not dumps).
h
holys

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/


print(j, file=f) in Python 3.6 (instead of print >> f, j)
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.
You can also use indent to create formatted dump: json.dump(content, file, indent=4)
m
mgilson
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 ...


json_string = json.dumps(d, , sort_keys=True) if sorted order is desired.
J
John La Rooy

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

j
jmhostalet

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)

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.
a
als0052

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.


d
davidvandebunte

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')