I have a dictionary, for example:
a = {'a':1,'b':2,'c':3}
And I want it to be saved in a json file.
How can I do this with the original python json library?
Please note that I am running Python 3.5.2, which has a build-in json library.
I have a dictionary, for example:
a = {'a':1,'b':2,'c':3}
And I want it to be saved in a json file.
How can I do this with the original python json library?
Please note that I am running Python 3.5.2, which has a build-in json library.
You can also dump json file directly using json.dump
instead of json.dumps
.
import json
a = {'a':1,'b':2,'c':3}
with open("your_json_file", "w") as fp:
json.dump(a , fp)
json.dumps
is mainly used to display dictionaries as a json format with the type of string. While dump is used for saving to file. Using this to save to file is obsolete.
The previous example only save the file to json but does not make it very pretty. So instead you could do this:
json.dump(a, fp, indent = 4) # you can also do sort_keys=True as well
# this work the same for json.dumps
This makes the json file more user friendly to read. the pydoc has some good description on how to use the json module.
To retrieve your data back, you can use the load
function.
a = json.load(fp) # load back the original dictionary
import json
a = {'name': 'John Doe', 'age': 24}
js = json.dumps(a)
# Open new json file if not exist it will create
fp = open('test.json', 'a')
# write to json file
fp.write(js)
# close the connection
fp.close()
show you code
#!/usr/bin/env python
# coding:utf-8
'''黄哥Python'''
import json
a = {'a': 1, 'b': 2, 'c': 3}
with open("json.txt", "w") as f:
f.write(json.dumps(a))
Most of other answers are correct but this will also print data in prettify and sorted manner.
import json
a = {'name': 'John Doe', 'age': 24}
js = json.dumps(a, sort_keys=True, indent=4, separators=(',', ': '))
with open('test.json', 'w+') as f:
f.write(js)