从 HTTP 回复返回的 JSON 中提取 UUID 值

从 HTTP 回复返回的 JSON 中提取 UUID 值

我正在尝试在 shellscript 中制作一个小脚本,从响应中获取一个 serviceUuid 并使用它。我只是在名为 Final.txt 的文件上打印服务器响应现在我需要提取“serviceUuid”之后的值:”

这是脚本:

uuid=$(curl   -X POST -H "ACCEPT-LANGUAGE:en"   -H "Content-Type: application/json"   -H "Accept: application/json" -d  {"username":"HereThereIsTheUsername"}  Here there is the url )

echo $uuid >> final.txt

这是回应:

{"status":{"code":"STATUS_OK","message":"ServiceUUID sent successfully via..."},"body":{"data":{"userApps":{},"username":"HereTheUsername","fullName":"NameOfTheAccountPossessor","lang":"sq","blocked":false,"lastLogin":"2016-10-10T17:19:22","passwordResetUuid":"6147dc32-b72e-450a-8084-2fdb5319a931","userAccessLevel":5,"countDownSeconds":0,"serviceUuid":"7260276c-5c3f-41d3-9329-3603acecb7e5","userAttributes":{},"labelMap":{},"id":"APPUSER00000012","someLabel":"NameOfTheOrganisation"}}}

那么有人可以帮我提取价值吗?

答案1

是一个JSON解析工具。你可以这样做:

uuid=$(curl ...)
service_uuid=$(jq -r '.body.data.serviceUuid' <<<"$uuid")
echo "$service_uuid"
7260276c-5c3f-41d3-9329-3603acecb7e5

答案2

现在我需要提取“serviceUuid”之后的值

因此,如果变量$uuid包含以下内容:

echo "$uuid"
{"status":{"code":"STATUS_OK","message":"ServiceUUID sent successfully via..."},"body":{"data":{"userApps":{},"username":"HereTheUsername","fullName":"NameOfTheAccountPossessor","lang":"sq","blocked":false,"lastLogin":"2016-10-10T17:19:22","passwordResetUuid":"6147dc32-b72e-450a-8084-2fdb5319a931","userAccessLevel":5,"countDownSeconds":0,"serviceUuid":"7260276c-5c3f-41d3-9329-3603acecb7e5","userAttributes":{},"labelMap":{},"id":"APPUSER00000012","someLabel":"NameOfTheOrganisation"}}}

...你呢仅有的想要这个serviceUuid值,我会这样做:

echo "$uuid" | sed -nE 's/.*"serviceUuid":"(.*)","user.*/\1/p'
7260276c-5c3f-41d3-9329-3603acecb7e5

在你的情况下,它看起来像:

echo "$uuid" | sed -nE 's/.*"serviceUuid":"(.*)","user.*/\1/p' >> final.txt

...将其附加到文件中final.txt


sed --version
sed (GNU sed) 4.2.2

答案3

没有“jq”,并且没有引号转义问题...尝试这个快速而简单的解决方案...

service_uuid=$( grep -oP '"serviceUuid":"\K[^"]+'  <<< "$uuid" )
  • <<< "$uuid字符串输入“grep”
  • -oP 选项意味着仅返回 perl 正则表达式的“匹配部分”。
  • perl-RE中的'\K'表示查找前面的部分,但只匹配后面的部分。

结果是它找到键并返回值(直到第一个引号)。

快速、小型、简单,并且适用于许多键值文件类型。

相关内容