在bash脚本中添加JSON元素

时间:2018-09-12 15:34:02

标签: json bash shell http

在我的bash脚本中,我有一行看起来像这样:

JOB_RESULTS=$(curl --fail -k -H "Content-Type: application/xml" --write-out HTTP_CODE='%{http_code}' "${request_url}")

此行输出以下内容:

{"name":"callCLF010Job","id":11693,"status":"STARTING","message":"The job has started.","exitCode":"exitCode=UNKNOWN;exitDescription="}HTTP_CODE=200

问题是,我想将HTTP_CODE添加到JSON消息中。

有没有办法使返回看起来像{"name":"callCLF010Job","id":11693,"status":"STARTING","message":"The job has started.","exitCode":"exitCode=UNKNOWN;exitDescription=","HTTP_CODE":"200"}

编辑:

随着五彩纸屑的更改,我的代码如下:

http_code="${JOB_RESULTS:${#JOB_RESULTS}-17}"
http_body="${JOB_RESULTS:0:${#JOB_RESULTS}-17}"
http_code_json=", ${http_code}}"
my_result="${http_body/%\}/$http_code_json}"

当我运行echo $my_result时,输出如下:

{"name":"callCLF010Job","id":11702,"status":"STARTING","message":"The job has started.","exitCode":"exitCode=UNKNOWN;exitDescriptio

2 个答案:

答案 0 :(得分:1)

一种选择是使用sed以所需的方式格式化输出:

echo $JOB_RESULTS | sed 's/}HTTP_CODE=\([0-9]\+\)$/,"HTTP_CODE":"\1"}/'

或在您的命令中:

JOB_RESULTS=$(curl --fail -k -H "Content-Type: application/xml" --write-out HTTP_CODE='%{http_code}' "${request_url}" | sed 's/}HTTP_CODE=\([0-9]\+\)$/,"HTTP_CODE":"\1"}/')

答案 1 :(得分:1)

这是使用shell parameter expansion完成工作。 (除了curl以外,还可以进行纯bash操作。)

curlout=$(curl -s --fail -k -H "Content-Type: application/xml" --write-out '"HTTP_CODE":"%{http_code}"' "http://example.com")
http_code="${curlout:${#curlout}-17}"
http_body="${curlout:0:${#curlout}-17}"
http_code_json=", ${http_code}}"
my_result="${http_body/%\}/$http_code_json}"

用您选择的URL或变量替换http://example.com

为了防止出现错误的URL或(否)输出时出错,您应该将最后四行放在if-construct中。例如。 if [[ $http_code != '"HTTP_CODE":"000"' ]]