JSON, jq, 合并文本 + 变量 + Bash 变量, 参数

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

JSON, jq, merged text + variable + bash variable, arguments

问题

I have translated the provided content for you:

我有类似的文件/数据:

```bash
$ echo "[{\"my_var1\":\"valueA\", \"my_var2\": \"valueB\"}]"
{"my_var1":"valueA", "my_var2": "valueB"}]

在我的代码中,我需要获取“my_var2”的值,很容易:

$ echo "[{\"my_var1\":\"valueA\", \"my_var2\": \"valueB\"}]" | \
jq -r ''.[] .my_var2''

# 正确的结果:
valueB

... 但是... 我需要使用bash变量来指定我想要获取的变量:

我不能指定“my_var2”,我必须只使用“var2”:

$ PART="var2"
$ echo "[{\"my_var1\":\"valueA\", \"my_var2\": \"valueB\"}]" | \
jq -r --arg JSONPART ${PART} ''.[] .my_[$JSONPART]''

期望的结果:

valueB

Please note that I've translated the content as requested, including the code portions.

<details>
<summary>英文:</summary>

I have similar file/data:

$ echo "[{&quot;my_var1&quot;:&quot;valueA&quot;, &quot;my_var2&quot;: &quot;valueB&quot;}]"
{"my_var1":"valueA", "my_var2": "valueB"}]


in my code I need to get value of &quot;my_var2&quot;, easy:

$ echo "[{&quot;my_var1&quot;:&quot;valueA&quot;, &quot;my_var2&quot;: &quot;valueB&quot;}]" |
jq -r '.[] .my_var2'

correct result:

valueB


... but ... I need to use bash variable to specify which variable I would like to get:

I can&#39;t specify &quot;my_var2&quot;, I have to use only &quot;var2&quot;

$ PART="var2"
$ echo "[{&quot;my_var1&quot;:&quot;valueA&quot;, &quot;my_var2&quot;: &quot;valueB&quot;}]" |
jq -r --arg JSONPART ${PART} '.[] .my_[$JSONPART]'

expected result:

valueB


</details>


# 答案1
**得分**: 2

The jq filter `.xyz` can be rewritten as `.[&quot;xyz&quot;]`. Thus:

```shell
$ PART=&#39;var2&#39;
$ echo &#39;[{&quot;my_var1&quot;:&quot;valueA&quot;, &quot;my_var2&quot;: &quot;valueB&quot;}]&#39; | \
jq -r --arg JSONPART &quot;$PART&quot; &#39;.[][&quot;my_&quot; + $JSONPART]&#39;
valueB

(Don't forget to properly quote your shell parameters when expanding!)

英文:

The jq filter .xyz can be rewritten as .[&quot;xyz&quot;]. Thus:

$ PART=&#39;var2&#39;
$ echo &#39;[{&quot;my_var1&quot;:&quot;valueA&quot;, &quot;my_var2&quot;: &quot;valueB&quot;}]&#39; | \
jq -r --arg JSONPART &quot;$PART&quot; &#39;.[][&quot;my_&quot; + $JSONPART]&#39;
valueB

(Don't forget to properly quote your shell parameters when expanding!)

答案2

得分: -1

This should work:

$ PART="var2"
$ echo "[{\"my_var1\":\"valueA\", \"my_var2\": \"valueB\"}]" | \
jq -r ".[] .my_$PART"
英文:

This should work:

$ PART=&quot;var2&quot;
$ echo &quot;[{\&quot;my_var1\&quot;:\&quot;valueA\&quot;, \&quot;my_var2\&quot;: \&quot;valueB\&quot;}]&quot; | \
jq -r &quot;.[] .my_$PART&quot;

huangapple
  • 本文由 发表于 2023年4月13日 16:57:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76003568.html
匿名

发表评论

匿名网友

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

确定