【问题标题】:Awk or other command how to get variable value on string curl results?awk 或其他命令如何获取字符串 curl 结果的变量值?
【发布时间】:2020-06-25 05:57:55
【问题描述】:

在 bash 脚本中,我正在为获取数据的 POST 请求运行 curl

f_curl_get_data (){

read -p "start date : " start_date
read -p "end date : " end_date

# (!) NOTE 
# - the date time format must be YYYY-MM-DD

mng_type=users
user=myuser
secret=mysecret

curl --location --request POST 'https://myapi.com/api/v2.1/rest/exports' \
    --header 'Content-Type: application/json' \
    --header 'SDK-APP-ID: '$user'' \
    --header 'SDK-SECRET: '$secret'' \
    --data-raw '{
        "type":"'$mng_type'",
        "start_date":"'$start_date'",
        "end_date": "'$end_date'"
    }' 

}

我得到以下结果

{"results":{"created_at":"2020-03-13T07:04:14Z","download_url":"","error_message":"","original_filename":"2020-03-13T07:04:14Z_exported_users.json","percentage":0,"resource_name":"users","size":0,"status":"started","total_rows":0,"unique_id":"37c23e60-5b83-404a-bd1f-6733ef04463b"},"status":200}

如何使用 awk 命令或其他命令从变量“unique_id”中获取值?

37c23e60-5b83-404a-bd1f-6733ef04463b

谢谢你

【问题讨论】:

  • 最好使用jq,因为这是 JSON 数据。

标签: bash ubuntu awk command


【解决方案1】:

使用 GNU awk 和 json 扩展:

$ gawk '
@load "json"                                # load extension
{
    lines=lines $0                          # in case of multiline json file
    if(json_fromJSON(lines,data)!=0) {      # explode valid json to an array
        print data["results"]["unique_id"]  # print the object value
        lines=""                            # in case there is more json left
    }
}' file

输出:

37c23e60-5b83-404a-bd1f-6733ef04463b

可以在那里找到扩展:

http://gawkextlib.sourceforge.net/json/json.html

...或者你可以使用jq:

$ jq -r '.results.unique_id' file
37c23e60-5b83-404a-bd1f-6733ef04463b

【讨论】:

  • 感谢您提供解决方案,非常感谢。
【解决方案2】:

使用 sed

sed -e 's/.*unique_id":"\(.*\)\"}.*/\1/'

演示:

:>echo '{"results":{"created_at":"2020-03-13T07:04:14Z","download_url":"","error_message":"","original_filename":"2020-03-13T07:04:14Z_exported_users.json","percentage":0,"resource_name":"users","size":0,"status":"started","total_rows":0,"unique_id":"37c23e60-5b83-404a-bd1f-6733ef04463b"},"status":200}' | sed -e 's/.*unique_id":"\(.*\)\"}.*/\1/'
37c23e60-5b83-404a-bd1f-6733ef04463b


【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-12
    • 2014-02-25
    • 1970-01-01
    • 2010-09-11
    • 2010-12-27
    • 2021-01-30
    • 2014-08-31
    相关资源
    最近更新 更多