Introduction

One of the most common tasks when working with data is to store it in a file format that can be easily shared across multiple platforms. JSON (JavaScript Object Notation) is a lightweight data interchange format that has become one of the most popular choices due to its simplicity and readability. In this tutorial, we will discuss how to dump JSON data in Python, which is a common operation that allows to convert Python objects into JSON format and write them to a file.

Table of Contents :

  • Dumping data to JSON Files
  • json.dump() Method
  • json.dumps() Method 

Dumping data to JSON Files :

  • In python we can dump data to Json files using 
    • dump method()
    • dumps method()
  • Steps for dumping data to Json file are as follows :
    • Import the json library using :  import json  
    • Ready the json data in dictionary format
    • Dump the data to a file

json.dump() Method :

  • To write data to a JSON file, we can use the  json.dump()  method. 
  • Arguments  : The dump  method takes two arguments: 
    • Data : The data that we want to write to the file. This can be a Python dictionary, list, or other data type. 
    • File : The file object that we want to write the data to. This can be created using the open() function
  • Code Sample : Here is a sample code of how to write data to a JSON file:

import json 

data = {'name': 'John Doe', 'age': 42, 'city': 'New York'} 

with open('data.json', 'w') as f: 
    json.dump(data, f) 

# In the example above, 
# we first import the json module. 
# We then create a Python dictionary with some data. 
# We then open a file called data.json in write mode. 
# We then use the json.dump() method to write the data to the file. 



json.dumps() Method :

  • We can also use the json.dumps() method to write data to a file. 
  • Arguments : This method takes only one argument - the data that we want to write to the file.
  • Dumps method returns a JSON-encoded string. 
  • Code Sample : Here is an sample code of how to use the  json.dumps()  method: 

import json 

data = {'name': 'John Doe', 'age': 42, 'city': 'New York'} 

with open('data.json', 'w') as f: 
   f.write(json.dumps(data))
   
   

Prev. Tutorial : Append data to json file

Next Tutorial : Load json data