JQ获取终端唯一值并按键过滤

西里尔·罗格农

我正在发现 jq,这是很棒的东西。在 GitHub 上发布了一些,他们告诉我在这里发布使用问题。

我正在尝试从 json 和过滤器中获取键/值列表,以保留属于列表/数组的每个键的唯一值。输入json是

{
"key0": {
"key1": "valueA",
"key2": 123456,
"key3": [{
  "key4": "anotherValue41",
  "key5": "anotherValue51",
  "key6": 999
}, {
  "key4": "anotherValue42",
  "key5": "anotherValue52",
  "key6": 666
}],
    "key10": {
        "key11": "lastvalue"
    }
}
}

我的 keyList 是

["key1","key2","key4","key5","key6","key9","key11"]

预期结果是仅保留与键列表匹配的键/值,并按键对值进行分组。

{
"key1": ["valueA"],
"key2": [123456],
"key4": ["anotherValue41", "anotherValue42"],
"key5": ["anotherValue51", "anotherValue52"],
"key6": [999, 666],
"key11": "lastvalue"
}

我曾尝试使用键,但我无法恢复到值……我发现的所有其他示例都具有重复的 json 结构。

我希望我足够清楚。

谢谢西里尔

顶峰

首先,让我们专注于解决问题,而不用担心keyList。

这可以通过使用tostream和以下辅助函数方便地完成

# s should be a stream of [key, value] pairs
def aggregate(s):
 reduce s as $x ({}; .[$x[0]] += [$x[1]] );

主过滤器可以写为:

aggregate( tostream
  | select(length==2 and (.[0][-1] | type == "string"))
  | [.[0][-1], .[1]] )

碰巧,这产生了原始问题的结果:

{
  "key1": [
    "valueA"
  ],
  "key11": [
    "lastvalue"
  ],
  "key2": [
    123456
  ],
  "key4": [
    "anotherValue41",
    "anotherValue42"
  ],
  "key5": [
    "anotherValue51",
    "anotherValue52"
  ],
  "key6": [
    999,
    666
  ]
}

键表

为了满足关于 keyList 的要求,我们假设列表作为$keyList.

然后我们可以通过简单地添加一个select条件来达到预期的结果index

aggregate( tostream
  | select(length==2 and (.[0][-1] | type == "string"))
  | [.[0][-1], .[1]]
  | select(.[0] as $k | $keyList|index($k) )) 

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章