Watch at Ease看見世界,讀懂生活。

科技 · 實用指南

jq 顯示 cannot index string with string?修改 filter 前先證明 JSON 形狀

保存 jq input mode 與每個 path 的 type,只守衛已證明的 mixed-shape 邊界並保留 rejects。

zh-TW jq JSON path type diagram
原創編輯插畫: prove the value type before indexing. Watch at Ease

jq 以 object key 索引 string、array、number 或 boolean 時會失敗。generator 可能先輸出有效值,再在另一 type 上失敗,留下 partial output 與非零 exit status。

保存原始 bytes、input mode 與精確 filter。建立 path-type ledger;schema drift 應失敗,合法 mixed collection 才使用窄守衛並保存 rejects。

凍結 bytes、mode 與 filter

保存代表性 input,記錄 jq --version、完整 filter、shell quoting、upstream 與 -R、-s、-n。-R 產生 string,-s 產生 array。

確認保存檔是 JSON,並排保留成功與失敗 record。先印出值再 exit 5 仍是失敗。

建立 path-type ledger

在 root 與每個 traversal step 執行 type。RFC 8259 定義 object 與 array,且 array elements 不必同型。

記錄 path、observed type 與 count。object 上的 .[] 會輸出所有 member values,後續 key 可能落到 string。

分開三種 shape failure

常見錯誤是錯誤 root traversal、mixed collection 與 stringified object。最後一種在解析前要先證明 provenance。

不要把 shell echo 當權威 bytes;quoting 可能改變內容。直接讀保存檔並和 producer schema 對照。

只守衛已證明邊界

合法 mixed collection 應先選 object 再讀 key,其他值連同 path 與 type 放入 reject ledger。

廣泛 try、catch 或 optional 會以 empty 隱藏錯誤;只有合約允許且 reject count 仍可見時才用。

要求 output、reject 與 exit 證據

測試 object、array、string、boolean、null、missing key 與 mixed array,並核對 counts 與 exit status。

完成需 input mode 清楚、path types 穩定、output count 正確、無未解 rejects,而且 object 變 scalar 時非零失敗。

zh-TW jq narrow guard and reject ledger diagram
原創編輯插畫: guard narrowly and keep rejected records visible. Watch at Ease