首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用jq变量(来自"as")查找键

使用jq变量(来自"as")查找键
EN

Stack Overflow用户
提问于 2019-12-18 02:53:42
回答 2查看 142关注 0票数 0

给定JSON如下:

代码语言:javascript
运行
复制
{"thing": ["hello", "bye"], "other": {"hello": "myval"}}

我想要一个jq表达式,它在"thing“下获取数组的第一个元素,并在"other”中查找它。所以我就这么做了:

代码语言:javascript
运行
复制
jq '.thing[0] as $tofind | .other.$tofind'

但我得到了

代码语言:javascript
运行
复制
jq: error: syntax error, unexpected '$', expecting FORMAT or QQSTRING_START (Unix shell quoting issues?) at <top-level>, line 1:
.thing[0] as $tofind | .other.$tofind
jq: 1 compile error

我尝试过很多其他的方法:

代码语言:javascript
运行
复制
echo '{"thing": ["hello", "bye"], "other": {"hello": "myval"}}' | jq '.thing[0] as $tofind | .other.($tofind)'
jq: error: syntax error, unexpected '(', expecting FORMAT or QQSTRING_START (Unix shell quoting issues?) at <top-level>, line 1:
.thing[0] as $tofind | .other.($tofind)
jq: 1 compile error
echo '{"thing": ["hello", "bye"], "other": {"hello": "myval"}}' | jq '.thing[0] as $tofind | .other.[($tofind)]'
jq: error: syntax error, unexpected '[', expecting FORMAT or QQSTRING_START (Unix shell quoting issues?) at <top-level>, line 1:
.thing[0] as $tofind | .other.[($tofind)]
jq: 1 compile error
echo '{"thing": ["hello", "bye"], "other": {"hello": "myval"}}' | jq '.thing[0] as $tofind | .other.[$tofind]'
jq: error: syntax error, unexpected '[', expecting FORMAT or QQSTRING_START (Unix shell quoting issues?) at <top-level>, line 1:
.thing[0] as $tofind | .other.[$tofind]
jq: 1 compile error
echo '{"thing": ["hello", "bye"], "other": {"hello": "myval"}}' | jq '.thing[0] as $tofind | .other.["$tofind"]'
jq: error: syntax error, unexpected '[', expecting FORMAT or QQSTRING_START (Unix shell quoting issues?) at <top-level>, line 1:
.thing[0] as $tofind | .other.["$tofind"]
jq: 1 compile error
echo '{"thing": ["hello", "bye"], "other": {"hello": "myval"}}' | jq '.thing[0] as $tofind | .other."$tofind"'
null
echo '{"thing": ["hello", "bye"], "other": {"hello": "myval"}}' | jq '.thing[0] as $tofind | .other."($tofind)"'
null

我在selectto_entries上找到了一种老套的解决方法,但我觉得必须有一种像样的方法来解决我所缺少的问题。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-12-18 03:37:35

代码语言:javascript
运行
复制
.thing[0] as $tofind | .other[$tofind]
票数 1
EN

Stack Overflow用户

发布于 2019-12-18 06:44:46

你可以简单地写下:

代码语言:javascript
运行
复制
jq '.other[.thing[0]]'
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59380424

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档