Dump JSON List to file Python
Contents Show
Python Write JSON to FileYou can convert any Python object to a JSON string and write JSON to File using json.dumps() function and file.write() function respectively. Following is a step by step process to write JSON to file.
Example 1: Write JSON (Object) to FileIn this example, we will convert or dump a Python Dictionary to JSON String, and write this JSON string to a file named data.json. Python Program import json aDict = {"a":54, "b":87} jsonString = json.dumps(aDict) jsonFile = open("data.json", "w") jsonFile.write(jsonString) jsonFile.close()Output Run the above program, and data.json will be created in the working directory. data.json {"a": 54, "b": 87}Example 2: Write JSON (List of Object) to FileIn this example, we will convert or dump Python List of Dictionaries to JSON string, and write this JSON string to file named data.json. Python Program import json aList = [{"a":54, "b":87}, {"c":81, "d":63}, {"e":17, "f":39}] jsonString = json.dumps(aList) jsonFile = open("data.json", "w") jsonFile.write(jsonString) jsonFile.close()Output Run the above program, and data.json will be created in the working directory. data.json [{"a": 54, "b": 87}, {"c": 81, "d": 63}, {"e": 17, "f": 39}]SummaryIn this tutorial of Python Examples, we learned how to write JSON to File, using step by step process and detailed example programs. Related Tutorials
|