代码之家  ›  专栏  ›  技术社区  ›  Josh

在bash脚本中添加JSON元素

  •  1
  • Josh  · 技术社区  · 7 年前

    在我的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 回复  |  直到 7 年前
        1
  •  1
  •   Murilo    7 年前

    一种方法是使用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"}/')
    
        2
  •  1
  •   confetti    7 年前

    这是使用 shell parameter expansion 完成任务。(除此之外,纯粹的恶作剧 curl

    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}"
    

    替换 http://example.com

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

    推荐文章