Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Shell 工具 jsondiff.sh:API 回歸測試的 JSON 比較利器

編輯:Linux 教學

重構歷史專案缺乏測試用例,不得不人工比對新舊服務回傳的 JSON 結果集。秉持「懶惰是程式設計師美德」的信條,開發了 jsondiff.sh 自動化比較工具。

核心邏輯與關鍵處理

  1. 抓取:curl 分別向新舊服務發請求獲取 JSON。
  2. 格式化:JSON 壓縮成單行無法直接 diff,需美化縮排;中文常被 Unicode 轉義(\uXXXX),需還原為可讀字符;欄位順序無語義差異,需按鍵名排序後再比較。
  3. 比較:優先 colordiff 彩色輸出,支援 vimdiff 視覺化,退回 diff -u。

PHP 實現的格式化函數

function ksort_recursive(&$array) {
    if (!is_array($array)) return;
    ksort($array);
    foreach (array_keys($array) as $key) {
        ksort_recursive($array[$key]);
    }
}
$options = JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE;
$array = json_decode($argn, true);
ksort_recursive($array);
echo json_encode($array, $options);

遞迴排序鍵名 + JSON_UNESCAPED_UNICODE 保留中文可讀性。

參數解析亮點:getopt 長選項

eval set -- $(getopt -q -o "h" -l "host:,uri:,old:,new:,vim,help" -- "$@")
while true; do
    case "$1" in
        --host) HOST=$2; shift 2;;
        --uri)  URI=$2; shift 2;;
        --old)  OLD=$2; shift 2;;
        --new)  NEW=$2; shift 2;;
        --vim)  VIM="Y"; shift 1;;
        -h|--help) usage; exit 0;;
        --) break;;
    esac
done

getopt 支援長選項、自動處理空格引號,配合 eval set -- 保留參數原始空白,比手寫 while getopts 更健壯。

使用範例

./jsondiff.sh --host=api.example.com --uri=/v1/users --old=10.0.0.1 --new=10.0.0.2
./jsondiff.sh --uri=/v1/order --old=old.svc --new=new.svc --vim  # 啟用 vimdiff

事後發現的更好工具

寫完才發現 jq —— 專業命令列 JSON 處理器,若早知曉可省去大量格式化代碼。姑且當作 Shell 腳本練習,留作備用。

Copyright © Windows教程網 All Rights Reserved