Python Logo

Json


What is JSON?

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy to read and write, and it is widely used in web development.

JSON data is represented as a collection of key-value pairs. The keys are strings, and the values can be strings, numbers, booleans, objects, or arrays.

Serializing Python objects to JSON

To serialize a Python object to JSON, you can use the json.dumps() function. The json.dumps() function takes a Python object as an argument and returns a JSON string representation of the object.

Example:

 

Python

import json

person = {
  "name": "John Doe",
  "age": 30,
  "occupation": "Software Engineer"
}

json_string = json.dumps(person)

print(json_string)
 

Output:

 

JSON

{"name": "John Doe", "age": 30, "occupation": "Software Engineer"}
 

Deserializing JSON to Python objects

To deserialize JSON to Python objects, you can use the json.loads() function. The json.loads() function takes a JSON string as an argument and returns a Python object representation of the string.

Example:

 

Python

import json

json_string = '{"name": "John Doe", "age": 30, "occupation": "Software Engineer"}'

person = json.loads(json_string)

print(person)
 

Output:

 

{'age': 30, 'name': 'John Doe', 'occupation': 'Software Engineer'}
 

Using JSON with Python libraries

Many Python libraries support JSON serialization and deserialization. For example, the requests library can be used to make HTTP requests and automatically deserialize the JSON responses.

Example:

 

Python

import requests

response = requests.get("https://example.com/api/users")

users = response.json()

print(users)
 

This code will make a GET request to the /api/users endpoint on the example.com domain. The response from the endpoint will be a JSON string. The requests.json() function will deserialize the JSON string into a Python list of users.

Conclusion

JSON is a powerful data-interchange format that can be used with Python to easily serialize and deserialize data. By understanding how to use JSON with Python, you can write more efficient and portable code.