json

Python JSON

Python JSON

JSON (JavaScript Object Notation) is a lightweight format for storing and exchanging data. Python provides a built-in module called json to work with JSON data.

Working with JSON in Python

You can use json.dumps() to convert a Python object into a JSON string and json.loads() to convert a JSON string back into a Python object:

      
        import json
        data = {"name": "Alice", "age": 25}
        json_data = json.dumps(data)  # Convert Python object to JSON string
        print("JSON data:", json_data)

        python_obj = json.loads(json_data)  # Convert JSON string to Python object
        print("Python object:", python_obj)
      
    

This code demonstrates how to serialize a Python object into JSON and then deserialize it back into a Python object.

Activity

Try It Yourself!

Write a Python program that reads a JSON file containing information about a person and prints the name and age of the person.

Quick Quiz

Quick Quiz

  1. What function do you use to convert a Python object into a JSON string?
  2. How do you convert a JSON string back into a Python object?

Answers: Use json.dumps() to convert a Python object into a JSON string. Use json.loads() to convert a JSON string back into a Python object.