Json loads vs Json Dumps
json.loads
and json.dumps
are two functions in Python’s json
library that serve opposite purposes when working with JSON data.
Here’s a breakdown of each:
1. json.loads
-
Purpose: Converts a JSON-formatted string into a Python dictionary (or other Python objects like lists, depending on the JSON structure).
-
Usage: Use
json.loads
when you receive JSON data as a string and want to work with it as a Python object.import json # JSON string json_string = '{"name": "Alice", "age": 25, "city": "New York"}' # Convert JSON string to Python dictionary data = json.loads(json_string) print(data) # Output: {'name': 'Alice', 'age': 25, 'city': 'New York'} print(data['name']) # Output: Alice
- Here,
json.loads
takes the JSON string and converts it to a dictionary so that you can work with it in Python.
- Here,
2. json.dumps
-
Purpose: Converts a Python dictionary (or other serializable Python objects) into a JSON-formatted string.
-
Usage: Use
json.dumps
when you want to convert Python data into a JSON string, often for saving to a file or sending over a network.import json # Python dictionary data = {"name": "Alice", "age": 25, "city": "New York"} # Convert Python dictionary to JSON string json_string = json.dumps(data) print(json_string) # Output: '{"name": "Alice", "age": 25, "city": "New York"}'
- Here,
json.dumps
takes the Python dictionary and converts it to a JSON string for easy storage or transmission.
- Here,
Key Differences
Function | Purpose | Input | Output |
---|---|---|---|
json.loads |
Parse JSON string to Python object | JSON string | Python object (dict, list, etc.) |
json.dumps |
Convert Python object to JSON string | Python object | JSON string |
Example Use Cases
json.loads
is useful when you receive JSON data from an API response or read JSON data from a file.json.dumps
is useful when you need to serialize Python data for storage, transmission, or saving to a JSON file.