This content originally appeared on DEV Community and was authored by Max
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)
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'}
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
This content originally appeared on DEV Community and was authored by Max
Max | Sciencx (2023-03-07T16:43:24+00:00) Read and Write Python Json. Retrieved from https://www.scien.cx/2023/03/07/read-and-write-python-json/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.