【问题标题】:Bash does not remove leading whitespaceBash 不会删除前导空格
【发布时间】: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 &gt; $tempjson; temp=$(cat $tempjson) 部分应该 not 是必要的——当您使用 $(curl ...) 时会运行 curl,而在展开 $thisjson 时不会重新运行。此外,您不需要在 bash 中的行尾使用分号。

标签: linux json bash scripting ifs


【解决方案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... ); 命令在字符串的开头生成的

所以如果第一个字符不是'{',请尝试删除第一个字符而不是空白字符

【讨论】:

  • 是的,这就是我认为我已经追踪到的——shell 上的任何东西都可以完美运行,但是这个命令似乎总是在前面加上一个空格。不过,喊得好——我没想到要从字符串中删除字符。
猜你喜欢
  • 2021-03-13
  • 1970-01-01
  • 2017-04-05
  • 2017-12-18
  • 1970-01-01
  • 1970-01-01
  • 2018-06-07
  • 1970-01-01
  • 2019-08-22
相关资源
最近更新 更多