Parsing JSON – Converting from JSON to Python
Parsing JSON String
The loads() method is used to parse JSON strings in Python and the result will be a Python dictionary.
Syntax:
json.loads(json_string)
Example: Converting JSON to a dictionary
Python3
# Python program to convert JSON to Dict import json # JSON string employee = '{ "name" : "Nitin" , "department" : "Finance" ,\ "company" : "GFG" }' # Convert string to Python dict employee_dict = json.loads(employee) print ( "Data after conversion" ) print (employee_dict) print (employee_dict[ 'department' ]) print ( "\nType of data" ) print ( type (employee_dict)) |
Data after conversion {'name': 'Nitin', 'department': 'Finance', 'company': 'GFG'} Finance Type of data <class 'dict'>
Note: For more information, refer to Parse Data From JSON into Python
Reading JSON file
load() method can read a file that contains a JSON object. Suppose you have a file named student.json that contains student data and we want to read that file.
Syntax:
json.load(file_object)
Example: Reading JSON file using Python
Let’s suppose the file looks like this.
Python3
# Python program to read # json file import json # Opening JSON file f = open ( 'data.json' ,) # returns JSON object as # a dictionary data = json.load(f) # Iterating through the json # list for i in data: print (i) # Closing file f.close() |
Output:
Note:
- JSON data is converted to a List of dictionaries in Python
- In the above example, we have used to open() and close() function for opening and closing JSON file. If you are not familiar with file handling in Python, please refer to File Handling in Python.
- For more information about readon JSON file, refer to Read JSON file using Python
JSON with Python
JSON (JavaScript Object Notation) is a file that is mainly used to store and transfer data mostly between a server and a web application. It is popularly used for representing structured data. In this article, we will discuss how to handle JSON data using Python. Python provides a module called json which comes with Python’s standard built-in utility.
Note: In Python, JSON data is usually represented as a string.
Contact Us