jq json将对象移动到嵌套对象并迭代未知名称/对象数

问题描述 投票:0回答:1

我一直在寻找几个'jq'解析json字符串的例子,都非常有用,但对我的特定问题没有定论

这是我的输入json:

{
    "outcome" : "TrBean",
    "result" : {"TrAct" : {
        "executiontime" : 16938570,
        "invocations" : 133863,
        "waittime" : 4981
    }}
}
{
    "outcome" : "WwwBean",
    "result" : {}
}
{
  "outcome": "CRFeatureBean",
  "result": {
    "CRChannels": {
      "executiontime": 78127,
      "invocations": 9983,
      "waittime": 213
    },
    "getCRChannels": {
      "executiontime": 98704,
      "invocations": 10113,
      "waittime": 212
    },
    "getCRToMigrate": {
      "executiontime": 32,
      "invocations": 4,
      "waittime": 0
    },
    "getCRId": {
      "executiontime": 28198633,
      "invocations": 747336,
      "waittime": 19856
    }
  }
}

我正在尝试通过collectd exec插件(PUTVAL)提供石墨,所以我需要一行中的信息。我尝试使用./jq '.result|to_entries[]|{"method:" .key, "inv": .value.invocations}|"PUTVAL \(.method)/invoke:\(.invokes)"' ......但我也需要在每一行都有“结果”。

另外,我不知道数量,也不知道结果对象的名称

所以,我想最终得到:

TrBean_TrAct
WwwBean
CRFeatureBean_CRChannels
CRFeatureBean_getCRChannels
CRFeatureBean_getCRToMigrate
CrFeatureBean_getCRId
json stream nested key jq
1个回答
0
投票

使用-r命令行选项调用jq时,以下jq过滤器将生成所需的输出:

((.result | keys_unsorted[]) // null) as $key
| if $key == null then .outcome
  else [.outcome, $key] | join("_")
  end

当然有许多可能的变化,例如

((.result | keys_unsorted[]) // null) as $key
| [.outcome, ($key // empty)]
| join("_")

或者如果你想要一个短的单行:

.outcome + ("_" + (.result | keys_unsorted[]) // null)

无论如何,这里简单的关键是生成.result的密钥作为流。处理“边缘情况”使解决方案稍微复杂一些,即.outcome + "_" + (.result | keys_unsorted[])

示例调用:jq -r -f program.jq input.json

© www.soinside.com 2019 - 2024. All rights reserved.