【发布时间】:2011-11-09 11:39:42
【问题描述】:
我似乎有一个很奇怪的问题。我正在尝试使用 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;
这会吐出几行(每个回显一个),直到“没有 JSON...解码”
{"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 的简单方法? 谢谢!
【问题讨论】:
-
试试
printf "%q\n" "$temp"——这至少会告诉你空白字符到底是什么(因为它表现得好像它不是一个正常的空格)。顺便说一句,echo $thisjson > $tempjson; temp=$(cat $tempjson)部分应该 not 是必要的——当您使用$(curl ...)时会运行 curl,而在展开 $thisjson 时不会重新运行。此外,您不需要在 bash 中的行尾使用分号。
标签: linux json bash scripting ifs