Introduction

JSON is a lightweight data interchange format that is widely used for storing and exchanging data in web applications. In this tutorial, we will focus on one particular aspect of working with JSON files - appending data. Specifically, we will show you how to use Python to append data to an existing JSON file, allowing you to easily update and expand your datasets as needed. Whether you are a beginner just getting started with Python or an experienced developer looking to enhance your skills, this tutorial will provide you with a practical and useful tool for working with JSON files in Python.

Table of Contents :

  • Appending to an Existing JSON File
  • Appending data to Json Using append method 

Appending to an Existing JSON File

  • To append data to an existing JSON file, 
    • first read the file's current data.
    • Then, update the data and 
    • write it back to the file.
  • Code Sample :

import json

with open("example.json", "r") as f:
   data = json.load(f)
data["grades"] = [90, 85, 95]

with open("example.json", "w") as f:
   json.dump(data, f, indent=4)
   
   
   

Appending data to Json using append method :

  • Assuming you have a JSON file named "input.json" 
  • with the following contents:  [ {"name": "John"}, {"name": "Jane"} ]  
  • to append a new entry to it, We can do the following: 
  • Code Sample :
import json 

with open('input.json', 'r') as file: 
   data = json.load(file) 

data.append({"name": "Mike"}) 

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

# This will result in the following contents in your "input.json" file: 
# [ {"name": "John"}, {"name": "Jane"}, {"name": "Mike"} ]



Prev. Tutorial : Writing to a json file

Next Tutorial : Dump json data