【发布时间】:2018-09-02 17:37:00
【问题描述】:
相关: Getting data from json using jq when key is numerical string 但不同,因为我将数字键存储在变量中。请参阅下面的示例。
文件temp.json:
{
"bccc26321e360ae5fde94aac81eef7c7270bbfd90de0787d0e5b45be4b21ce53": {
"size": 189,
"fee": 0.00000678,
"modifiedfee": 0.00000678,
"time": 1535906461,
"height": 539665
},
"43906c7227610cd58a1c95714e4f79cd46e0d98ae3f4214f1b2cf325b628b70e": {
"size": 256,
"fee": 0.00008328,
"modifiedfee": 0.00008328,
"time": 1535906461,
"height": 539665
}
}
尝试使用变量进行索引:
#get second key 43906c7227610cd58a1c95714e4f79cd46e0d98ae3f4214f1b2cf325b628b70e
>txid=$(cat temp.json | jq 'keys' | jq .[1] | tr -d '"')
>cat temp.json | jq .$txid
jq: error: syntax error, unexpected IDENT, expecting $end (Unix shell quoting issues?) at <top-level>, line 1:
.43906c7227610cd58a1c95714e4f79cd46e0d98ae3f4214f1b2cf325b628b70e
jq: 1 compile error
>cat temp.json | jq '.$txid'
q: error: syntax error, unexpected '$' (Unix shell quoting issues?) at <top-level>, line 1:
.$txid
jq: error: try .["field"] instead of .field for unusually named fields at <top-level>, line 1:
.$txid
jq: 2 compile errors
>cat temp.json | jq '."$txid"'
null
想要的输出很简单
>cat temp.json | jq '."43906c7227610cd58a1c95714e4f79cd46e0d98ae3f4214f1b2cf325b628b70e"'
{
"size": 256,
"fee": 0.00008328,
"modifiedfee": 0.00008328,
"time": 1535906461,
"height": 539665
}
【问题讨论】:
-
如果你想要key周围的引号,你为什么要通过
tr删除它们?有了你所拥有的,我希望".\"$txid\""能够工作;如果你放弃tr -d '"',".$txid"可能就足够了。 -
它解决了我的问题,谢谢
-
已将其添加为答案;如果您能接受,将不胜感激。
-
顺便说一句,运行
jq ... temp.json或jq ... <temp.json或<temp.json jq ...比运行cat temp.json | jq ...更好——运行cat意味着jq必须从单独的程序中读取 FIFO(@ 987654336@) 可以访问文件,而不是让jq直接访问输入文件。
标签: json linux bash command-line jq