How to Handle JSON file in Python

Normally in Python, We use several data types to store data such as Lists, Tuples, Sets, and Dictionaries. But If we want to add something to the data through user input, We can add and view only while running the program. If we stop the program and run again we loose what we add earlier.

To give a solution to manage the data permanently, there are various ways. Today we are going to see how to handle(store, add, remove, read) a JSON file in Python

1. Read a JSON File

Let's create a file called data.json as follows,

data.json

JSON is an object which includes key-value pairs.
In my example, biodata is a key where a list is a value for that key. The list contains two dictionaries(Objects).

Let's create a file called data.py as follows,

data.py

  • I have imported json first. Then only I can use json object
  • I have open my json file(data.json) with "r"(read) mode and assigned to a variable called f
  • If I open on read mode I can only read the file, can not edit the file
  • Loaded complete data into a variable called data
  • You can see the output down where same as the data stored in json file
  • Then I have closed the file
Try these examples and see
print(data['biodata'])
biodata = data['biodata']
print("Hello ",biodata[0]['name'])

2. Add or Remove to JSON file

data.py
  • Once the data is assigned to a variable I can add or remove or edit the data as I want
  • After modifying, We have to open the JSON file on "w"(Write) mode
  • Using json.dump() function we are telling what is new data set and to which file it should be stored.
Hope this is useful for beginners to understand how to handle JSON file in Python.
For more details, WhatsApp or Twitter

Thank You



Comments

Popular posts from this blog

Search results in MySQL database using PHP

Introduction to React Native Navigation