JSON
Introduction to Python
Getting Started
Comments
Variables
Data Types
Type Casting
Input and Output
Operators
Strings
Booleans
Conditional Statements
While Loop
For Loop
Loop Control Statements
Lists
Tuples
Sets
Dictionaries
Functions
Function Arguments and Return Values
Variable Scope
Recursion
Lambda Functions
Arrays and Python Lists
Modules
Dates and Math
String Formatting
File Handling
Try and Except
Classes and Objects
Inheritance
Iterators
JSON
RegEx
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 alist, andtrue/falsevalues becomeTrue/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()andjson.dump()(without the "s").
Example
Executing...
❌ Error:
✅ Output:
// Click Run ▶ to execute