Open In App

Python JSON

Last Updated : 15 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Python JSON JavaScript Object Notation is a format for structuring data. It is mainly used for storing and transferring data between the browser and the server. Python too supports JSON with a built-in package called JSON. This package provides all the necessary tools for working with JSON Objects including parsing, serializing, deserializing, and many more. 

JSON Example

Let’s see a simple example where we convert the JSON objects to Python objects and vice versa.

Convert from JSON to Python object

Let’s see a simple example where we convert the JSON objects to Python objects. Here, json.loads() method can be used to parse a valid JSON string and convert it into a Python Dictionary.

Python3




import json
  
# JSON string
employee = '{"id":"09", "name": "Nitin", "department":"Finance"}'
print("This is JSON", type(employee))
  
print("\nNow convert from JSON to Python")
  
# Convert string to Python dict
employee_dict = json.loads(employee)
print("Converted to Python", type(employee_dict))
print(employee_dict)


Output:

This is JSON <class 'str'>

Now convert from JSON to Python
Converted to Python <class 'dict'>
{'id': '09', 'name': 'Nitin', 'department': 'Finance'}

Convert from Python object to JSON

Let’s see a simple example where we convert Python objects to JSON objects. Here json.dumps() function will convert a subset of Python objects into a JSON string.

Python3




import json
  
# JSON string
employee_dict = {'id': '09', 'name': 'Nitin', 'department': 'Finance'}
print("This is Python", type(employee_dict))
  
print("\nNow Convert from Python to JSON")
  
# Convert Python dict to JSON
json_object = json.dumps(employee_dict, indent=4)
print("Converted to JSON", type(json_object))
print(json_object)


Output:

This is Python <class 'dict'>

Now Convert from Python to JSON
Converted to JSON <class 'str'>
{
    "id": "09",
    "name": "Nitin",
    "department": "Finance"
}

JSON in Python

This JSON Tutorial will help you learn the working of JSON with Python from basics to advance, like parsing JSON, reading and writing to JSON files, and serializing and deserializing JSON using a huge set of JSON programs.

JSON in Python

Introduction

Reading and Writing JSON

Parsing JSON

Serializing and Deserializing JSON

Conversion between JSON

More operations JSON



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads