Home Tutorials Python Tutorial JSON
JSON

JSON


Working with JSON

Definition: JSON (JavaScript Object Notation) is a lightweight, text-based format used for storing and transporting data. In Python, the built-in json module provides tools to convert JSON strings into Python dictionaries and vice versa.

Why: JSON is the universal language of data exchange on the web. Web applications, APIs, and configuration files rely heavily on JSON to send data back and forth between a server and a client or between different applications.

Common JSON Operations

  • Parsing JSON (Decoding): Converting a JSON string into a Python object (like a dictionary or list) using json.loads().
  • Converting to JSON (Encoding): Converting a Python object into a clean JSON formatted string using json.dumps().

Example (Parsing JSON)

import json

# A sample JSON string (looks like a Python dictionary, but enclosed in single quotes)
x = '{"name":"Ravi","age":20}'

# Convert the JSON string into a Python dictionary
y = json.loads(x)

# Accessing data using standard dictionary keys
print(y["name"])  # Output: Ravi

Key Notes

  • Data Type Mapping: When you parse a JSON string, Python automatically converts JSON types to its native types (e.g., a JSON object becomes a Python dict, an array becomes a list, and true/false values become True/False).
  • File Operations: If you want to read or write JSON data directly from or to an external physical file rather than working with text strings, you use json.load() and json.dump() (without the "s").
Example

🏋️ Test Yourself With Exercises

Take our quiz on JSON to test your knowledge.

Exercise »