【问题标题】:JQ getting terminal unique values and filtering by keysJQ获取终端唯一值并按键过滤
【发布时间】:2018-07-16 21:53:18
【问题描述】:

我正在发现 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 结构。

我希望我足够清楚。

谢谢 西里尔

【问题讨论】:

  • 不要忘记接受并投票赞成帮助您解决问题的答案或评论您在这些答案中遇到的问题。一个有趣的问题,但在未来,请包括您解决问题的尝试。祝你好运。

标签: json key jq


【解决方案1】:

首先,让我们专注于解决问题,而不用担心 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 的形式提供。

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

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

【讨论】:

  • 这太棒了!谢啦。您能否详细说明或指向一些文档以完全理解 [.[0][-1], .[1]] 和 select(length==2 and (.[0][-1] | type == “细绳”)) ?再次感谢你。你摇滚
  • 我将从教程stedolan.github.io/jq/tutorial 开始,然后浏览手册中最相关的部分。我很高兴收到有关以下内容的任何反馈:github.com/pkoppstein/jq/wiki/…
猜你喜欢
  • 1970-01-01
  • 2013-06-22
  • 1970-01-01
  • 1970-01-01
  • 2021-12-29
  • 2017-04-16
  • 1970-01-01
  • 2019-02-18
  • 2022-10-30
相关资源
最近更新 更多