英文:
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 "[{"my_var1":"valueA", "my_var2": "valueB"}]"
{"my_var1":"valueA", "my_var2": "valueB"}]
in my code I need to get value of "my_var2", easy:
$ echo "[{"my_var1":"valueA", "my_var2": "valueB"}]" |
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't specify "my_var2", I have to use only "var2"
$ PART="var2"
$ echo "[{"my_var1":"valueA", "my_var2": "valueB"}]" |
jq -r --arg JSONPART ${PART} '.[] .my_[$JSONPART]'
expected result:
valueB
</details>
# 答案1
**得分**: 2
The jq filter `.xyz` can be rewritten as `.["xyz"]`. Thus:
```shell
$ PART='var2'
$ echo '[{"my_var1":"valueA", "my_var2": "valueB"}]' | \
jq -r --arg JSONPART "$PART" '.[]["my_" + $JSONPART]'
valueB
(Don't forget to properly quote your shell parameters when expanding!)
英文:
The jq filter .xyz
can be rewritten as .["xyz"]
. Thus:
$ PART='var2'
$ echo '[{"my_var1":"valueA", "my_var2": "valueB"}]' | \
jq -r --arg JSONPART "$PART" '.[]["my_" + $JSONPART]'
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="var2"
$ echo "[{\"my_var1\":\"valueA\", \"my_var2\": \"valueB\"}]" | \
jq -r ".[] .my_$PART"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论