在這裏插入圖片描述

在Python中檢查JSON文件的語法,有多種方法可以實現。強烈推薦使用現成的庫,因為它們更穩定、高效且經過充分測試。

1. 使用標準庫 json(推薦)

Python內置的json模塊是最簡單直接的方法:

import json

def validate_json_file(file_path):
    """
    驗證JSON文件語法是否正確
    """
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            json.load(f)
        print(f"✅ {file_path} 是有效的JSON文件")
        return True
    except json.JSONDecodeError as e:
        print(f"❌ {file_path} 包含語法錯誤:")
        print(f"   錯誤位置: 第{e.lineno}行, 第{e.colno}列")
        print(f"   錯誤信息: {e.msg}")
        return False
    except FileNotFoundError:
        print(f"❌ 文件 {file_path} 不存在")
        return False

# 使用示例
validate_json_file('data.json')

2. 使用 jsonschema 進行結構驗證(高級)

如果需要驗證JSON的結構而不僅僅是語法,可以使用jsonschema庫:

pip install jsonschema
import json
import jsonschema
from jsonschema import validate

# 定義JSON schema
schema = {
    "type": "object",
    "properties": {
        "name": {"type": "string"},
        "age": {"type": "number", "minimum": 0},
        "email": {"type": "string", "format": "email"}
    },
    "required": ["name", "age"]
}

def validate_json_with_schema(file_path, schema):
    """
    使用schema驗證JSON文件結構和內容
    """
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            data = json.load(f)
        
        validate(instance=data, schema=schema)
        print(f"✅ {file_path} 符合schema定義")
        return True
        
    except jsonschema.ValidationError as e:
        print(f"❌ 數據驗證失敗: {e.message}")
        return False
    except json.JSONDecodeError as e:
        print(f"❌ JSON語法錯誤: {e}")
        return False

# 使用示例
validate_json_with_schema('user.json', schema)

3. 使用 json.tool 命令行工具

Python還提供了命令行工具來驗證和格式化JSON:

# 驗證JSON文件
python -m json.tool data.json

# 如果JSON無效,會顯示錯誤信息
# 如果有效,會輸出格式化後的JSON

4. 完整的驗證函數

下面是一個功能更完整的驗證函數:

import json
import os

def comprehensive_json_validation(file_path, schema=None):
    """
    綜合的JSON文件驗證
    """
    # 檢查文件是否存在
    if not os.path.exists(file_path):
        print(f"❌ 文件 {file_path} 不存在")
        return False
    
    # 檢查文件是否為空
    if os.path.getsize(file_path) == 0:
        print(f"❌ 文件 {file_path} 為空")
        return False
    
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            data = json.load(f)
        
        print(f"✅ {file_path} - 語法驗證通過")
        
        # 可選:schema驗證
        if schema:
            try:
                from jsonschema import validate
                validate(instance=data, schema=schema)
                print(f"✅ {file_path} - 結構驗證通過")
            except ImportError:
                print("⚠️  未安裝jsonschema庫,跳過結構驗證")
            except Exception as e:
                print(f"❌ 結構驗證失敗: {e}")
                return False
        
        return True
        
    except json.JSONDecodeError as e:
        print(f"❌ JSON語法錯誤:")
        print(f"   位置: 第{e.lineno}行, 第{e.colno}列")
        print(f"   錯誤: {e.msg}")
        
        # 提供更詳細的錯誤上下文
        with open(file_path, 'r', encoding='utf-8') as f:
            lines = f.readlines()
            if e.lineno <= len(lines):
                error_line = lines[e.lineno - 1]
                print(f"   錯誤行: {error_line.rstrip()}")
                print(f"   {' ' * (e.colno - 1)}^")
        
        return False
    except UnicodeDecodeError:
        print(f"❌ 文件編碼錯誤,請使用UTF-8編碼")
        return False

# 使用示例
comprehensive_json_validation('data.json')

5. 批量驗證多個文件

import glob

def validate_multiple_json_files(pattern):
    """
    批量驗證多個JSON文件
    """
    files = glob.glob(pattern)
    results = {}
    
    for file_path in files:
        print(f"\n正在驗證: {file_path}")
        is_valid = validate_json_file(file_path)
        results[file_path] = is_valid
    
    print(f"\n驗證結果彙總:")
    for file_path, is_valid in results.items():
        status = "✅ 有效" if is_valid else "❌ 無效"
        print(f"  {file_path}: {status}")
    
    return results

# 驗證所有.json文件
validate_multiple_json_files("*.json")

總結

  • 簡單語法檢查:使用內置json模塊的json.load()
  • 結構驗證:使用jsonschema
  • 命令行工具:使用python -m json.tool
  • 避免自己寫解析器:JSON的邊界情況很多,自己寫容易出錯

推薦使用第一種方法,因為它簡單、可靠且無需額外依賴。對於複雜項目,可以結合第二種方法進行結構驗證。


結束語 Flutter是一個由Google開發的開源UI工具包,它可以讓您在不同平台上創建高質量、美觀的應用程序,而無需編寫大量平台特定的代碼。我將學習和深入研究Flutter的方方面面。從基礎知識到高級技巧,從UI設計到性能優化,歡飲關注一起討論學習,共同進入Flutter的精彩世界!