The Wayback Machine - https://web.archive.org/web/20240527155131/https://www.geeksforgeeks.org/append-to-json-file-using-python/
Open In App

Append to JSON file using Python

Last Updated : 26 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The full form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-string which contains the value in key-value mapping within { }. 

Functions Used: 
 

  • json.loads(): json.loads() function is present in python built-in ‘json’ module. This function is used to parse the JSON string.
     

Syntax: json.loads(json_string)
Parameter: It takes JSON string as the parameter.
Return type: It returns the python dictionary object. 

  • json.dumps(): json.dumps() function is present in python built-in ‘json’ module. This function is used to convert Python object into JSON string.
     

Syntax: json.dumps(object)
Parameter: It takes Python Object as the parameter.
Return type: It returns the JSON string. 
 

  • update(): This method updates the dictionary with elements from another dictionary object or from an iterable key/value pair.
     

Syntax: dict.update([other])
Parameters: Takes another dictionary or an iterable key/value pair.
Return type: Returns None. 


Example 1: Updating a JSON string.
  

Python3
# Python program to update
# JSON
import json

# JSON data:
x = '{ "organization":"GeeksForGeeks","city":"Noida","country":"India"}'

# python object to be appended
y = {"pin":110096}

# parsing JSON string:
z = json.loads(x)

# appending the data
z.update(y)

# the result is a JSON string:
print(json.dumps(z))

Output:
 

{“organization”: “GeeksForGeeks”, “city”: “Noida”, “country”: “India”, “pin”: 110096}


Example 2: Updating a JSON file. Suppose the JSON file looks like this.
 

python-json

We want to add another JSON data after emp_details. Below is the implementation.

Python3
# Python program to update
# JSON


import json


# function to add to JSON
def write_json(new_data, filename='data.json'):
    with open(filename,'r+') as file:
          # First we load existing data into a dict.
        file_data = json.load(file)
        # Join new_data with file_data inside emp_details
        file_data["emp_details"].append(new_data)
        # Sets file's current position at offset.
        file.seek(0)
        # convert back to json.
        json.dump(file_data, file, indent = 4)

    # python object to be appended
y = {"emp_name":"Nikhil",
     "email": "nikhil@geeksforgeeks.org",
     "job_profile": "Full Time"
    }
    
write_json(y) 

Output:
 

python-append-json


 


Similar Reads

How To Append Data To Yaml File Using Python
We are given a YAML file and our task is to append data inside that YAML file by using different approaches in Python. In this article, we will see how we can append data to YAML file using Python. We have data.yml file containing the following data and we will append the data inside this file. data.yaml GeeksforGeeks: EducationAppend Data To Yaml
3 min read
Python append to a file
While reading or writing to a file, access mode governs the type of operations possible in the opened file. It refers to how the file will be used once it's opened. These modes also define the location of the File Handle in the file. The definition of these access modes is as follows: Append Only (‘a’): Open the file for writing.Append and Read (‘a
4 min read
Python - Append content of one text file to another
Having two file names entered by users, the task is to append the content of the second file to the content of the first file with Python. Append the content of one text file to anotherUsing file objectUsing shutil moduleUsing fileinput moduleSuppose the text files file1.txt and file2.txt contain the following data. file1.txt file2.txt Append the c
3 min read
Append Data To Binary File In Python
We are given a binary file and our task is to append data into that binary file in Python using different approaches. In this article, we will see how we can append data to binary file in Python. Append Data to Binary File in Python below, are the examples of Append Data To Binary File In Python: Appending String Datatype Append List of Integers Ap
3 min read
Append Text or Lines to a File in Python
Appending text or lines to a file is a common operation in programming, especially when you want to add new information to an existing file without overwriting its content. In Python, this task is made simple with built-in functions that allow you to open a file and append data to it. In this tutorial, we'll explore what it means to append text or
3 min read
Python - Difference between json.dump() and json.dumps()
JSON is a lightweight data format for data interchange which can be easily read and written by humans, easily parsed and generated by machines. It is a complete language-independent text format. To work with JSON data, Python has a built-in package called json. Note: For more information, refer to Working With JSON Data in Python json.dumps() json.
2 min read
Python - Difference Between json.load() and json.loads()
JSON (JavaScript Object Notation) is a script (executable) file which is made of text in a programming language, is used to store and transfer the data. It is a language-independent format and is very easy to understand since it is self-describing in nature. Python has a built-in package called json. In this article, we are going to see Json.load a
3 min read
How to append a new row to an existing csv file?
For writing a CSV file, the CSV module provides two different classes writer and Dictwriter. Here we will discuss 2 ways to perform this task effectively. The First will be 'append a list as a new row to the existing CSV file' and second way is 'Append a dictionary as a new row to the existing CSV file.' First, let's have a look at our existing CSV
3 min read
How to Append Pandas DataFrame to Existing CSV File?
In this discussion, we'll explore the process of appending a Pandas DataFrame to an existing CSV file using Python. Add Pandas DataFrame to an Existing CSV File. To achieve this, we can utilize the to_csv() function in Pandas with the 'a' parameter to write the DataFrame to the CSV file in append mode. Pandas DataFrame to_csv() Syntax Syntax : df.t
3 min read
Read JSON file using Python
The full form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-
4 min read
Article Tags :
Practice Tags :