DEV Community

Mr #1738
Mr #1738

Posted on

Writing JSON to a file

Here you will be able to write into a json file in a few with help of the below code:

import json 

person_dict = {
    "name":"vincent",
    "languages": ["English","French"],
    "married": False,
    "age": 24
}

with  open('person.txt', 'w') as json_file:
    json.dump(person_dict, json_file)
Enter fullscreen mode Exit fullscreen mode

First we import the json module, which provides functions for working with JSON data,We have a Python dictionary called person_dict that contains information about a person, including their name, languages, marital status, and age.

The with open('person.txt', 'w') as json_file: statement opens a file called 'person.txt' in write mode if the file exists it doesn't exist it is created automatically. The with statement ensures that the file is properly closed after we finish using it, even if an exception occurs.

Inside the with block, we use the json.dump() function to write the contents of the person_dict dictionary as JSON data into the json_file. The json.dump() function takes two arguments: the Python object to be serialized (in this case, the dictionary), and the file object to which the JSON data should be written. In this code, the person_dict is written as JSON into the file specified by json_file.

output: you should able to see a file created called person.txt and contains the following data.

 {"name": "vincent", "languages": ["English", "French"], "married": false, "age": 24}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)