DEV Community

Cover image for Read and Write Python Json
Max
Max

Posted on

Read and Write Python Json

JSON(stands for JavaScript Object Notation) is a lightweight text based format for representing data in structured format. JSON is often used for exchanging data between a web server and a client in web applications. It can be used with any programming language that can parse and generate JSON data.

In this article we will learn how to read and write json file using python. Python have the inbuild package to handle json.

Python dictionary and JSON are similar in terms of their syntax, but both are different. Python dictionary is a built-in data structure that stores a collection of key-value pairs in a mutable way, only exist in memory. Where as JSON is a lightweight data interchange format, can store in physical storage for later use.

Let see how to write a json to a file using python

Using the write w operation in with and json dump we have converted the dictionary data to json file.

import json

data = {
    "name": "George",
    "age": 35,
    "phone": "409-356-4961"
}

with open("jsonfile.json", "w") as file:
    json.dump(data, file)
Enter fullscreen mode Exit fullscreen mode

write json file using python

How to read a json file using python

We are going to use the read r operation in with an use json loads to convert the json data to back to dictionary.

import json

with open("jsonfile.json", "r") as file:
    data = json.load(file)

print("data:", data)

# Output:
data: {'name': 'George', 'age': 35, 'phone': '409-356-4961'}
Enter fullscreen mode Exit fullscreen mode

Explore Other Related Articles

Python List Comprehension
How to combine two dictionaries in python using different methods
How to check if a key exists in a dictionary python
Python try exception tutorial
Python classes and objects tutorial
Python Recursion Function Tutorial

Top comments (0)