filmov
tv
Python One‑Liner: Pretty‑Print JSON String for Readability! 🔄📑 #PythonTips #CodingShorts

Показать описание
Pretty‑printing JSON transforms a compact, hard‑to‑read JSON string into a human‑friendly format by adding newlines and indentation
This is invaluable when working with API responses, configuration files, or log data in Python
Long Way Explanation:
Output: Print the resulting multi‑line string for easy inspection
One‑Liner Explanation:
Combine parsing and formatting into a single expression:
This leverages the JSON module’s built‑in methods for concise, readable code
By relying on Python’s standard library, this approach avoids external dependencies and handles complex JSON structures—including nested lists and objects—robustly
Use this one‑liner in Jupyter notebooks or shell scripts to streamline debugging, logging, and data exploration workflows
Codes:
Long Way: Load and dump with json module
import json
s = '{"name":"Alice","age":30,"languages":["Python","JavaScript"],"active":true}'
# Parse JSON string into Python object
# Serialize with indentation and sorted keys
print(pretty)
# Output the formatted JSON
One‑Liner: Chain loads and dumps
# Output:
# {
# "active": true,
# "age": 30,
# "languages": [
# "Python",
# "JavaScript"
# ],
# "name": "Alice"
# }
This is invaluable when working with API responses, configuration files, or log data in Python
Long Way Explanation:
Output: Print the resulting multi‑line string for easy inspection
One‑Liner Explanation:
Combine parsing and formatting into a single expression:
This leverages the JSON module’s built‑in methods for concise, readable code
By relying on Python’s standard library, this approach avoids external dependencies and handles complex JSON structures—including nested lists and objects—robustly
Use this one‑liner in Jupyter notebooks or shell scripts to streamline debugging, logging, and data exploration workflows
Codes:
Long Way: Load and dump with json module
import json
s = '{"name":"Alice","age":30,"languages":["Python","JavaScript"],"active":true}'
# Parse JSON string into Python object
# Serialize with indentation and sorted keys
print(pretty)
# Output the formatted JSON
One‑Liner: Chain loads and dumps
# Output:
# {
# "active": true,
# "age": 30,
# "languages": [
# "Python",
# "JavaScript"
# ],
# "name": "Alice"
# }