【发布时间】:2019-03-20 20:06:32
【问题描述】:
希望大家都好。
我正在努力使用 JQ 尝试使用特定键从输入 json 中选择字符串值数组以进行选择。 "key":["string1",... , "stringn"] 可以嵌入到 json 中任何深度的“某处”。我只知道数组的键值。
假设我有一些 json,其中包括键 dictionnay (dict) 和 json source (source)。在这个例子中,我想选择 "key4" 和 "key11" 数组,并将它们放入带有相应键的结果 json 中。
我的示例输入是:
{
"dict": ["key4", "key11"],
"source":{
"key0": {
"key1": "valueA",
"key2": 123456,
"key3": [{
"key4": ["anotherValue4341", "anotherValue4342"],
"key5": [{
"someKey351": "someValue351"
}, {
"someKey352": "someValue352"
}],
"key6": 999
},
{
"key7": "anotherValue342",
"key8": "anotherValue352",
"key9": 666
}
],
"key10": {
"key11": ["lastvalue111", "lastvalue112", "lastvalue113"]
}
}
}}
我对这个样本的预期输出是:
{
"key4": ["anotherValue4341", "anotherValue4342"],
"key11": ["lastvalue111", "lastvalue112", "lastvalue113"]
}
我正在使用 JQ 来提取请求的输出。
现在我尝试重用以前的查询来选择这样的键/值:
jq '.dict as $dict | .source | reduce paths as $p (.;getpath($p) as $v| if $v|type == "string" and $dict[$v] then setpath($p; $dict[$v]) else . end)'
但它似乎与某些值有冲突:jq: error (at :26): Cannot index array with string "valueA"
我还尝试选择包含 dict 中的键的匹配对象:
jq '.dict as $dict | .source | recurse(.[]?) | objects | select(in($dict))'
但这会导致错误“无法检查数组是否有对象键”
我希望我能清楚地解释我的需求/问题。
任何提示表示赞赏。
【问题讨论】: