【问题标题】:How do I get a string from a curl response for a variable in bash?如何从 bash 中的变量的 curl 响应中获取字符串?
【发布时间】:2018-11-04 18:41:01
【问题描述】:

bash 脚本发送一个 curl。 curl响应示例如下:

{"code":"2aaea70fdccd7ad11e4ee8e82ec26162","nonce":1541355854942}

我需要获取代码“2aaea70fdccd7ad11e4ee8e82ec26162”(不带引号)并在 bash 脚本中使用它。

【问题讨论】:

    标签: bash curl grep


    【解决方案1】:

    使用jq 从 JSON 中提取值,并使用命令替换来捕获命令的输出:

    code=$(curl ... | jq -r '.code')
    

    -r (--raw) 直接打印字符串,而不是像在 JSON 中那样引用它。

    【讨论】:

    • jenkins 中的这个请求“BUILD_STATUS=$(curl --silent ${BUILD_URL}api/json | jq -r '.result')”给了我“解析错误:第 1 行的数字文字无效,第 18 列"
    • 第 1 行第 18 列是什么?
    • 你的意思是在 curl 的 json 响应中?
    • @YoussefBoudaya:是的。它显然在抱怨它不是一个有效的 JSON。
    • {"_class":"hudson.model.FreeStyleBuild","actions":[{"_class":"hudson.model.CauseAction","causes":[{"_class":" hudson.model.Cause$UserIdCause","shortDescription":"Démarré par l'utilisateur Youssef Boudaya","userId":"youssefboudaya","userName":"Youssef Boudaya"}]}, ...
    【解决方案2】:

    不想安装jq也可以通过sed命令实现:

    json=`curl ...`
    code=$(echo "$json" | sed -nE 's/.*"code":"([^\"]*)",".*/\1/p')
    

    【讨论】:

    • JSON 中通常不保证键的顺序。
    • {"unused":{"code":"wrong_code"},"code":"correct_code"} - 不要使用正则表达式解析 json,使用适当的 json 解析器。还有{"code":"code_with_\"_lol"}
    • @hanshenrik 我明白你的意思,但该解决方案是专门针对这个问题中所述的问题设计的,而不是通用的。无论如何感谢您的评论
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-13
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-28
    • 2020-06-27
    相关资源
    最近更新 更多