python
  1. python-json-handling

Python JSON Handling

Syntax

In order to use JSON in Python, you need to import the json module first. Here is the basic syntax for using JSON in Python:

import json

Example

Suppose you have a Python dictionary my_dict:

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

You can convert this dictionary into JSON format using the dumps() method:

import json

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

json_object = json.dumps(my_dict)

print(json_object)

The output will be:

{"name": "John", "age": 30, "city": "New York"}

Explanation

The json.dumps() method takes a Python object as input and returns a string in JSON format. In the above example, we have passed the Python dictionary my_dict to the dumps() method, and it has returned a JSON string.

Similarly, you can convert a JSON string into a Python object using the loads() method:

import json

json_str = '{"name": "John", "age": 30, "city": "New York"}'

python_dict = json.loads(json_str)

print(python_dict)

The output will be:

{'name': 'John', 'age': 30, 'city': 'New York'}

Use

JSON is widely used for data exchange between web servers and clients. In Python, you can use JSON to store and exchange data between different applications.

Important Points

  • json.dumps() method converts a Python object into a JSON string.
  • json.loads() method converts a JSON string into a Python object.
  • JSON supports a limited set of data types, such as strings, numbers, boolean values, arrays, and objects.
  • Python objects such as lists and tuples can be converted to JSON arrays, while Python dictionaries can be converted to JSON objects.

Summary

In this tutorial, you learned how to handle JSON data in Python. You learned how to convert a Python object into a JSON string using the json.dumps() method and how to convert a JSON string into a Python object using the json.loads() method. You also learned about the limitations of JSON and how to convert Python objects to JSON arrays and objects.

Published on: