×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Writing JSON to a file in Python

By IncludeHelp Last updated : February 20, 2024

To write JSON to a file, you can use the combination of json.dumps() method and file handling in Python. The json.dumps() method converts a Python object to a JSON string, opens the file in "w" mode, and writes the JSON string to a file.

Syntax

Below is the code to write JSON to a file:

with open("sample_file.json", "w") as out:
	json.dump(json_data, out)

Python program to write JSON to a file

This program writes a given JSON object to a file in Python.

# Code to write JSON to a file

# Importing json moduke
import json

# Python object to be written
json_data = {
    "id": "101",
    "name": "ALex",
    "age": 21,
    "phonenumber": "8818923409"
}

# Writing to a file
with open("sample_file.json", "w") as out:
    json.dump(json_data, out)

Output

The output of the above program is:

File's data: sample_file.json
{"id": "101", "name": "ALex", "age": 21, "phonenumber": "8818923409"}

To understand the above program, you should have the basic knowledge of the following Python topics:

 
 
Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.