w1coding.comAll tutorials

Python JSON

Python lessons
  1. Environment Setup
  2. Introduction
  3. Control
  4. Control
  5. Loops
  6. Functions
  7. Lists
  8. Dictionary
  9. Classes
  10. Exception
  11. File
  12. Libray
  13. Date
  14. Regula
  15. JSON
  16. Web
  17. Zweb
  18. Apis
  19. Unity
  20. Llampda
  21. Iterators
  22. Generators
  23. Files
  24. Context
  25. Ilogging
  26. Multithreading
  27. Networking
  28. SQLite

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.