json - 使用 jq 循环遍历 json 文件

标签 json linux bash command-line jq

相关: 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
      }

最佳答案

如果你想要的是 ."xxx" 作为参数,那么使用 ".\"$txid\""。 如果您删除 tr -d '"'".$txid" 甚至可能就足够了。

关于json - 使用 jq 循环遍历 json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52139494/

相关文章:

c# - 对如何在 C# 中使用 JSON 感到困惑

mysql - 对于空值,SQlite select 返回 "(null)"而不是 ""

java - 为什么我的 Java 代码无法正确执行 bash 命令?

bash - ImageMagick - 透明背景上的 Alpha 蒙版

regex - Sed 使用正则表达式从文件中删除时间戳

javascript json为每个当前元素创建父元素

java - Playframework 结果检查如何工作

json - 属性配置的值必须是环境变量具有字符串(或简单类型)属性的对象

linux - 仅当其 ASCII 格式文件时,shell one-liner 才能对文件进行分类

linux - 如何告诉 rpm 查看特定目录的依赖项?