JSON with Python - GeeksforGeeks

19 Nov, 2021
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.
To use any module in Python it is always needed to import that module. We can import json module by using the import statement.
Example: Importing JSON module
Python3
# importing json moduleimport json
  
The load() and loads() functions of the json module makes it easier to parse JSON object. 
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 stringemployee ='{"name": "Nitin", "department":"Finance",\"company":"GFG"}' # Convert string to Python dictemployee_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
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 filef = open('data.json',) # returns JSON object as# a dictionarydata = json.load(f) # Iterating through the json# listfor i in data:    print(i) # Closing filef.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
dump() and dumps() method of json module can be used to convert from Python object to JSON.
The following types of Python objects can be converted into JSON strings:
dict
list
tuple
string
int
float
True
False
None
Python objects and their equivalent conversion to JSON:
dumps() method can convert a Python object into a JSON string.
Syntax:
json.dumps(dict, indent)
It takes two parameters:
dictionary: name of dictionary which should be converted to JSON object.
indent: defines the number of units for indentation
Example: Converting Python dictionary to JSON string
Python3
# Python program to convert# Python to JSON  import json # Data to be writtendictionary = {    "name": "sunil",    "department": "HR",    "Company": 'GFG'} # Serializing jsonjson_object = json.dumps(dictionary)print(json_object)
{"name": "sunil", "department": "HR", "Company": "GFG"}

Note: For more information about converting JSON to string, refer to Python – Convert to JSON string
dump() method can be used for writing to JSON file.
Syntax:
json.dump(dict, file_pointer)
It takes 2 parameters:
dictionary: name of a dictionary which should be converted to a JSON object.
file pointer: pointer of the file opened in write or append mode.
Example: Writing to JSON File
Python3
# Python program to write JSON# to a file  import json # Data to be writtendictionary ={    "name" : "Nisha",    "rollno" : 420,    "cgpa" : 10.10,    "phonenumber" : "1234567890"} with open("sample.json", "w") as outfile:    json.dump(dictionary, outfile)
Output:
In the above example, you must have seen that when you convert the Python object to JSON it does not get formatted and output comes in a straight line. We can format the JSON by passing the indent parameter to the dumps() method.
Example: Formatting JSON
Python3
# Import required librariesimport json # Initialize JSON datajson_data = '[ {"studentid": 1, "name": "Nikhil", "subjects": ["Python", "Data Structures"]},\{"studentid": 2, "name": "Nisha", "subjects": ["Java", "C++", "R Lang"]} ]' # Create Python object from JSON string# datadata = json.loads(json_data) # Pretty Print JSONjson_formatted_str = json.dumps(data, indent=4)print(json_formatted_str)
[
    {
        "studentid": 1,
        "name": "Nikhil",
        "subjects": [
            "Python",
            "Data Structures"
        ]
    },
    {
        "studentid": 2,
        "name": "Nisha",
        "subjects": [
            "Java",
            "C++",
            "R Lang"
        ]
    }
]
Note: For more information, refer to Pretty Print JSON in Python
We can sort the JSON data with the help of the sort_keys parameter of the dumps() method. This parameter takes a boolean value and returns the sorted JSON if the value passed is True. By default, the value passed is False.
Example: Sorting JSON
Python3
# Import required librariesimport json # Initialize JSON datajson_data = '[ {"studentid": 1, "name": "Nikhil", "subjects":\["Python", "Data Structures"], "company":"GFG"},\{"studentid": 2, "name": "Nisha", "subjects":\["Java", "C++", "R Lang"], "company":"GFG"} ]' # Create Python object from JSON string# datadata = json.loads(json_data) # Pretty Print JSONjson_formatted_str = json.dumps(data, indent=4, sort_keys=True)print(json_formatted_str)
[
    {
        "company": "GFG",
        "name": "Nikhil",
        "studentid": 1,
        "subjects": [
            "Python",
            "Data Structures"
        ]
    },
    {
        "company": "GFG",
        "name": "Nisha",
        "studentid": 2,
        "subjects": [
            "Java",
            "C++",
            "R Lang"
        ]
    }
]
prachisoda1234
simmytarika5
Python-json
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Python Classes and Objects
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Pandas dataframe.groupby()
Create a directory in Python