1

私は非常に奇妙な問題を抱えているようです。jsawk を使用して CURL コマンドから JSON フィールド値を取得しようとしていますが、jsawk には JSON がきれいに印刷されている必要があります (「python -mjson.tool」のおかげで、適切にフォーマットされた JSON ファイルで簡単に実現できます)。

問題は、JSON ファイル/文字列の先頭に空白がある (これは違法です) ことですが、それを削除できないようです。

 {"response": {"status": {"version": "4.2", "code": 5, "message": "The Identifier specified does not exist"}}}

いくつかのオプションは、スクリプトとは無関係に機能します (例: echo ~/m.json | sed -e 's/^[ \t]*//')

{"response": {"status": {"version": "4.2", "code": 5, "message": "The Identifier specified does not exist"}}}

違いを見ます?ただし、次のすべての方法で目的の結果が得られるわけではありません。コマンドラインの動作をエミュレートするために、文字列を sed にパイプしてみましたが、うまくいきませんでした。誰かが私を正しい方向に向けることができますか?

thisjson=$(curl -F "api_key=$apikey" -F "format=json" -F "md5=$thismd5" -F... );
echo $thisjson > $tempjson; #Req'd else bash re-evals curl command
temp=$(cat $tempjson);      #Read string back to variable
echo $temp;                 #Try several methods to strip ws
temp="${temp##+([[:space:]])}";
echo $temp;
temp=$(sed -e 's/^[[:space:]]*//' <<<"$temp")
echo "|${temp}|";
temp=$(echo ${temp/ /} );
temp="${temp#"${temp%%[![:space:]]*}"}"
echo $temp;                #Try piping string directly
thisprettyjson=$(echo $temp | sed -e 's/^[ \t]*//' |python -mjson.tool);
echo $thisprettyjson;

「No JSON ...decoded」まで、複数の行(エコーごとに1行)を吐き出します

 {"response": {"status": {"version": "4.2", "code": 5, "message": "The Identifier specified does not exist"}}}
...
 {"response": {"status": {"version": "4.2", "code": 5, "message": "The Identifier specified does not exist"}}}
No JSON object could be decoded

私が見逃したばかげた何かがあると確信しています。おそらく他に言及すべき唯一のことは、IFS を Space/Tab/NL から単に NL に変更したことです。

誰でもアイデアはありますか?または、JSON を解析するための別の簡単な方法はありますか? ありがとう!

4

1 に答える 1

1

これを使用してテストを行いました:

tempjson='tempjson.txt'
thisjson=' {"response": {"status": {"version": "4.2", "code": 5, "message": "The Identifier specified does not exist"}}}'
echo $thisjson > $tempjson; #Req'd else bash re-evals curl command
...

わたしにはできる:

{"response": {"status": {"version": "4.2", "code": 5, "message": "The Identifier specified does not exist"}}}
|{"response": {"status": {"version": "4.2", "code": 5, "message": "The Identifier specified does not exist"}}}|

$(curl -F "api_key=$apikey" -F "format=json" -F "md5=$thismd5" -F... );したがって、コマンドによって文字列の先頭に生成される特別なスペース文字があると思います

したがって、「{」でない場合は、空白文字の代わりに最初の文字を削除してみてください

于 2011-11-09T11:59:35.187 に答える