Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> ระบบ >> Linux

Pretty Print JSON ใน Python: 2 วิธีง่ายๆ

JSON ที่ minified (บีบอัด whitespace) อ่านยาก Pretty print = เพิ่ม indentation, line breaks ให้อ่านง่าย Python มี json module built-in ทำได้ง่ายมาก

วิธีที่ 1: Python Script (ควบคุมรายละเอียดได้)

#!/usr/bin/env python3
import json
import sys

# 1. กำหนดไฟล์ JSON
json_file = "addresses.json"  # หรือ sys.argv[1] เพื่อรับจาก command line

# 2. อ่านและ parse
with open(json_file, 'r') as f:
    parsed = json.load(f)

# 3. Pretty print (stdout)
print(json.dumps(parsed, indent=4, sort_keys=True))

# 4. หรือเขียนกลับไฟล์
# with open('pretty_addresses.json', 'w') as f:
#     json.dump(parsed, f, indent=4, sort_keys=True)

พารามิเตอร์สำคัญ:

  • indent=4: เว้นวรรค 4 spaces ต่อ level (ใช้ 2, 4, หรือ "\t" ได้)
  • sort_keys=True: เรียง key ตามตัวอักษร
  • ensure_ascii=False: รองรับ Unicode (ไทย, อีโมจิ) โดยไม่ escape

วิธีที่ 2: One-liner Command Line (เร็วที่สุด ไม่ต้องเขียนไฟล์)

cat addresses.json | python3 -m json.tool

หรือระบุไฟล์โดยตรง:

python3 -m json.tool addresses.json

Output จะ pretty print มาที่ stdout ทันที

ตัวอย่างผลลัพธ์

ก่อน (minified):

{"users":[{"id":1,"name":"Somchai","email":"somchai@example.com"},{"id":2,"name":"Somsri","email":"somsri@example.com"}]}

หลัง (pretty):

{
    "users": [
        {
            "email": "somchai@example.com",
            "id": 1,
            "name": "Somchai"
        },
        {
            "email": "somsri@example.com",
            "id": 2,
            "name": "Somsri"
        }
    ]
}

เคล็ดลับเพิ่มเติม

  • Validate JSON: python3 -m json.tool file.json > /dev/null && echo "Valid"
  • จัดการไฟล์ใหญ่: ใช้ ijson (iterative parser) แทน json.load()
  • Colorize output: pipe ไป pygmentize -l json หรือ jq . file.json (jq เร็วกว่าและสีสัน)

Pretty print JSON ใน Python ทำได้ทั้ง script และ one-liner เลือกใช้ตามสถานการณ์!