Skip to content

Python create JSON file from dict

  • by

You can create JSON files from dict using a built-in module json. We need to use json.dump() method to do this.

json.dump(developer, write_file, indent=4)

Use the indent parameter to prettyPrint your JSON data. You can also use sort_keys to sort dictionary keys while writing it in the JSON file.

Python creates a JSON file from a dictionary example

Simple example code.

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

Output:

Python create JSON file from dict

Or use this code json.dump instead of json.dumps. This is an easier way to do it.

json.dumps is mainly used to display dictionaries in a json format with the type of string. While dump is used for saving to file. Using this to save to a file is obsolete.

import json

a = {'name': 'John Doe', 'age': 24}

with open("sample.json", "w") as outfile:
json.dump(a, outfile)

Do comment if you have any doubts or suggestions on this Python JSON file topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading