Read and Write JSON to File in Python
In this tutorial, we will share with you how to Read and Write JSON to File using Python.JSON is commonly used by web applications to transfer data between client and server.
JSON (JavaScript Object Notation) is an easy-to-read format for interchange data. It is the text form of a javascript object. The key is of type “string “with double quotation marks and values can be string, number, or nested JSON. Python has a built-in JSON module that accept a JSON string and convert into a dictionary.
Write JSON Data to a File
Now we can use
with
and open
method to create a new file and write content into the file. We will convert dictionary data to json object using json.dumps()
and write to file using write()
method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#write-program.py import json data = { "usermame" : "admin", "name": "Tech Arise" "email" : "admin@techarise.com", "password" : "admin", } userObject = json.dumps(data, indent = 4) with open("user.json", "w") as outFile: outFile.write(userObject) |
Read JSON File in Python
In the above example, we read a JSON file. In this example, we will read a JSON string and parse it into a dictionary using
json.loads()
1 2 3 4 5 6 7 8 9 10 |
#read-program.py import json with open('user.json', 'r') as openFile: userObject = json.load(openFile) print(userObject) print(type(userObject)) |
Output:
1 2 |
{'username': 'admin', 'name': 'Tech Arise', 'email': 'admin@techarise.com', 'password': 'admin'} <class 'dict'> |