我正在发现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结构。
我希望我说得够清楚了。
谢谢西里尔
发布于 2018-07-17 06:11:05
首先,让我们专注于解决这个问题,而不用担心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的要求,让我们假设列表以$keyList
的形式提供。
然后,我们可以通过使用index
简单地添加一个select
条件来达到预期的结果
aggregate( tostream
| select(length==2 and (.[0][-1] | type == "string"))
| [.[0][-1], .[1]]
| select(.[0] as $k | $keyList|index($k) ))
https://stackoverflow.com/questions/51370588
复制相似问题