Python JSON Tutorial - Create, Read, Parse JSON
In this article, you will learn how to create, read and parse JSON using Python. JSON (JavaScript Object Notation) is popular among developers for data serialization. It is a data format consisting of key-value pairs. It is used widely to transmit and receive data between a server and a web application in JSON format. It is so popular that every modern programming language has methods to generate and parse JSON formatted data.
Import JSON
Before getting started to work on JSON, first we need to import the json library. This library contains all the necessary methods to work on JSON.
import JSON
Python Generate JSON File (dict to json)
Here, we have mentioned how to generate a JSON file from dict or to convert python dict to json. The JSON library provides json.dumps() method for writing data to a JSON file. The data can be a dict, list, tuple, string. The following example converts the dict containing a student record to JSON format.
import json
# Python Dict
student = {
"Roll": 1001,
"firstname": "Priska",
"lastname": "Kashyap",
"class": 10,
"section": "A",
"address": {
"street address": "11 1nd Street",
"city": "New York",
"state": "NY",
"postal code": "10021"
}
}
# convert dict to JSON:
stud_json = json.dumps(student, indent=2, sort_keys=True)
# Print JSON
print(stud_json)
Output of the above code
The above code returns the following JSON formatted data.
{
"Roll": 1001,
"address": {
"city": "New York",
"postal code": "10021",
"state": "NY",
"street address": "11 1nd Street"
},
"class": 10,
"firstname": "Priska",
"lastname": "Kashyap",
"section": "A"
}
Python Read JSON file (json to dict)
The JSON library contains json.load() method to read a file containing JSON object. Suppose we have a JSON file 'student.json'.
{
"Roll": 1001,
"address": {
"city": "New York",
"postal code": "10021",
"state": "NY",
"street address": "11 1nd Street"
},
"class": 10,
"firstname": "Priska",
"lastname": "Kashyap",
"section": "A"
}
The below code reads the above JSON file and converts it to dict using Python
import json
with open('student.json') as f:
data = json.load(f)
print(data)
Output of the above code -
The above code returns the following dictionary from a JSON file.
{'Roll': 1001, 'address': {'city': 'New York', 'postal code': '10021', 'state': 'NY', 'street address': '11 1nd Street'}, 'class': 10, 'firstname': 'Priska', 'lastname': 'Kashyap', 'section': 'A'}
Python JSON to String
The above example reads the JSON file and converts it to dictionary. But, we can also get the data in a string format. The following code reads the JSON file and converts it into a string.
import json
with open('student.json') as f:
data = json.load(f)
print(type(data))
result = json.dumps(data)
print(result)
print(type(result))
Output
The above code returns the following string from a JSON file.
<class 'dict'>
{"Roll": 1001, "address": {"city": "New York", "postal code": "10021", "state": "NY", "street address": "11 1nd Street"}, "class": 10, "firstname": "Priska", "lastname": "Kashyap", "section": "A"}
<class 'str'>
Python Parse JSON Data
Here, we have decoded or parsed the JSON data in Python file -
import json
with open('student.json') as f:
data = json.load(f)
print("Roll No - "+ str(data['Roll']))
print("First Name - "+ data['firstname'])
print("Last Name - "+ data['lastname'])
print("Class - "+ str(data['class']))
print("Section - "+ data['section'])
print("Address - ")
print(data['address']['street address'])
print(data['address']['city'])
print(data['address']['state'])
print(data['address']['postal code'])
Output
The above code parsed the following data from a JSON file.
Roll No - 1001
First Name - Priska
Last Name - Kashyap
Class - 10
Section - A
Address -
11 1nd Street
New York
NY
10021
Related Articles
Convert list to dictionary PythonDictionary inside list Python
Pandas string to datetime
Convert Excel to CSV Python Pandas
Python add list to list
Python Pandas Dataframe to CSV
Python compare two lists
Remove element from list Python
Python iterate list with index
How to draw different shapes using Python Pygame
Python send email to multiple recipients
How to generate QR Code in Python using PyQRCode
Python programs to check Palindrome strings and numbers
CRUD operations in Python using MYSQL Connector
Fibonacci Series Program in Python
Python File Handler - Create, Read, Write, Access, Lock File
Python convert XML to JSON
Python convert xml to dict
Python convert dict to xml