解決 Windows 版本 jq 解析 json 檔案遇到 syntax error, unexpected INVALID_CHARACTER, expecting $end

jq 是解析 json 檔案的命令列工具。Windows 版本 jq 解析 json 檔案遇到 syntax error, unexpected INVALID_CHARACTER, expecting $end 錯誤訊息。解決方式是 (1) 移除 <jq filter> 的單引號或改成雙引號、或者直接 (2) 改用 CygWin 版本的 jq。


錯誤狀況


1. 從官方網站下載 Windows 版本 jq
2. 打開命令提示字元,輸入指令 jq-win64.exe <jq filter> C:\path\to\json_file
jq: error: syntax error, unexpected INVALID_CHARACTER, expecting $end (Windows cmd shell quoting issues?) at <top-level>, line 1:
''
jq: 1 compile error

解決方式 1

jq - windows examples · Issue #392 · stedolan/jq 提到 shell 處理單引號發生錯誤。將框住 <jq filter> 的單引號移掉或者改成雙引號即可解決問題。

範例:
原本: jq-win64.exe '.' c:\path\to\json_file
改成: jq-win64.exe . c:\path\to\json_file

解決方式 2

1. 下載與安裝 Cygwin
2. 安裝 jq package
(1) Search 輸入框輸入 jq 並不會搜尋到任何 package

(2) 點選 View 下拉選單,從 Pending 改成 Full。下方才會搜尋到 jq 的 package

(3) 在 New 欄位原本是 Skip 選擇旁邊的下拉選單

(4) 選擇要安裝的 jq 版本,此處選擇最新版本

(5) 按下一步


(6) 完成安裝,打開 CygWin 輸入指令 jq 確認已經完成安裝

$ jq
jq - commandline JSON processor [version 1.5]
Usage: jq [options] <jq filter> [file...]
        jq is a tool for processing JSON inputs, applying the
        given filter to its JSON text inputs and producing the
        filter's results as JSON on standard output.
        The simplest filter is ., which is the identity filter,
        copying jq's input to its output unmodified (except for
        formatting).
        For more advanced filters see the jq(1) manpage ("man jq")
        and/or https://stedolan.github.io/jq
        Some of the options include:
         -c             compact instead of pretty-printed output;
         -n             use `null` as the single input value;
         -e             set the exit status code based on the output;
         -s             read (slurp) all inputs into an array; apply filter to it;
         -r             output raw strings, not JSON texts;
         -R             read raw strings, not JSON texts;
         -C             colorize JSON;
         -M             monochrome (don't colorize JSON);
         -S             sort keys of objects on output;
         --tab  use tabs for indentation;
         --arg a v      set variable $a to value <v>;
         --argjson a v  set variable $a to JSON value <v>;
         --slurpfile a f        set variable $a to an array of JSON texts read from <f>;
        See the manpage for more options.


3. 安裝 jq package 後,輸入指令 


$ where cat
C:\cygwin64\bin\cat.exe

$ where jq
C:\cygwin64\bin\jq.exe

4. 電腦 -> 內容 -> 進階系統設定 -> 環境變數 -> 使用者變數 -> 編輯 PATH 變數:加入「C:\cygwin64\bin\」方便呼叫 cat 與 jq 兩隻程式

5. 打開命令提示字元,輸入指令 cat C:\path\to\json_file | jq <jq filter> 即可順利解析 json 檔案


無效的嘗試

修改 json 檔案內容,嘗試過使用 (1) Unicode 文字編碼或不編碼、(2) 檔案結尾加上 windows 換行字元四種組合狀況,都會遇到相同問題。

參考資料






留言