Awk или другая команда, как получить значение переменной по результатам строки curl? - PullRequest
0 голосов
/ 13 марта 2020

в скрипте bash я запускаю curl для POST-запроса, получающего данные

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}

как мне просто получить значение из переменной "unique_id" с помощью команды awk или другого?

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

спасибо u

Ответы [ 2 ]

1 голос
/ 13 марта 2020

Использование 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


1 голос
/ 13 марта 2020

Использование 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
...