如何从JSON输出中提取两个属性值并将它们分别分配给Bash中的专用变量?

huangapple go评论44阅读模式
英文:

How to extract two attribute values from a json output and assign each of them to a dedicated variable in bash?

问题

请注意:

~$ az ad sp show --id $spn_id --query '[appId, displayName]'
[
  "c...1",
  "xyz"
]

~$

我想将每个返回的值分配给它们各自的Bash变量,即APP_IDAPP_DISPLAY_NAME。我的当前解决方案如下:

~$ read -r APP_ID APP_DISPLAY_NAME < <(az ad sp show --id $spn_id --query '[appId, displayName]' -o tsv)
~$

这也能正常工作:

~$ echo $APP_ID
c...1

~$ echo $APP_DISPLAY_NAME
xyz

~$
英文:

Please, observe:

~$ az ad sp show --id $spn_id --query &#39;[appId, displayName]&#39;
[
  &quot;c...1&quot;,
  &quot;xyz&quot;
]

~$

I would like to assign each returned value to its own bash variable, namely to APP_ID and APP_DISPLAY_NAME respectively. My current solution is this:

~$ x=(`az ad sp show --id $spn_id --query &#39;[appId, displayName]&#39; -o tsv | tr -d &#39;\r&#39;`)

~$ APP_ID=${x[0]}

~$ APP_DISPLAY_NAME=${x[1]}

~$

Which works fine:

~$ echo $APP_ID
c...1

~$ echo $APP_DISPLAY_NAME
xyz

~$

I am curious if it is possible to do it in a more concise way?

答案1

得分: 1

是的,使用jq是最清晰的方法:

str='[
  "c...1",
  "xyz"
]'

# 通过使用'.[N]'语法获取数组中的第N个项目
app_id=$(jq -r '.[0]' <<< "$str")

# 'jq'需要通过标准输入传递输入字符串。使用'<<<'来实现
app_display_name=$(jq -r '.[1]' <<< "$str")

printf '%s\n' "id: $app_id"
printf '%s\n' "name: $app_display_name"
英文:

Yes, using jq would be the cleanest way:

str=&#39;[
  &quot;c...1&quot;,
  &quot;xyz&quot;
]&#39;

# The &#39;.[N]&#39; syntax gets the Nth item in the array
app_id=$(jq -r &#39;.[0]&#39; &lt;&lt;&lt; &quot;$str&quot;)

# &#39;jq&#39; requires feeding the input string through standard input. use the &#39;&lt;&lt;&lt;&#39; to do so
app_display_name=$(jq -r &#39;.[1]&#39; &lt;&lt;&lt; &quot;$str&quot;)

printf &#39;%s\n&#39; &quot;id: $app_id&quot;
printf &#39;%s\n&#39; &quot;name: $app_display_name&quot;

答案2

得分: 1

您可以使用以下命令与 sedxargs 结合使用:

export $(az ad sp show --id $spn_id --query '[appId, displayName]' | tr -d "\n" | sed -E "s/\[\s+(.+)\,\s+(.+)\]/APP_ID=\"\" \nAPP_DISPLAY_NAME=\"\"/" | xargs -L 1)

然后,您可以使用以下命令来输出 APP_IDAPP_DISPLAY_NAME 的值:

echo $APP_ID
echo $APP_DISPLAY_NAME

输出会是:

c...1
xyz
英文:

You can use the following with sed and xargs:

export $( az ad sp show --id $spn_id --query &#39;[appId, displayName]&#39; | tr -d &quot;\n&quot; | sed -E  &quot;s/\[\s+(.+)\,\s+(.+)\]/APP_ID=\&quot;\&quot; \nAPP_DISPLAY_NAME=\&quot;\&quot;/&quot; | xargs -L 1)

~$ echo $APP_ID
c...1

~$ echo $APP_DISPLAY_NAME
xyz

huangapple
  • 本文由 发表于 2023年2月10日 10:06:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/75406284.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定