使用jq根据出现在成员列表中的元素过滤JSON列表

时间:2019-08-03 11:56:49

标签: json jq

我正在使用jq尝试根据列表中对象内部列表的内容来过滤JSON列表。这是我的JSON文档的示例:

{
  "modules": [
    {
      "path": [
        "root"
      ],
      "outputs": {
        "a": "b",
        "c": "d"
      }
    },
    {
      "path": [
        "other1"
      ],
      "outputs": {
        "e": "f",
        "g": "h"
      }
    },
    {
      "path": [
        "other2"
      ],
      "outputs": {
        "i": "j",
        "k": "l"
      }
    }
  ]
}

我想将modules列表过滤到path列表包含“ root”的对象,然后返回outputs对象。本质上我想返回:

{"a":"b","c":"d"}

我可以使用jq .modules[0].outputs(请参阅example on http://jqplay.org)来做,但我不想假设我感兴趣的对象是modules的第0个元素列表,相反,我想过滤modules列表,其中path列表包含元素“ root”。

我该怎么做?

2 个答案:

答案 0 :(得分:1)

通常,一旦我发布问题,我就会通过反复试验偶然发现答案。

.modules[] | select(.path == ["root"]).outputs

请参阅example on jqplay.org

enter image description here

答案 1 :(得分:0)

让我不仅为您提供解决方案,还为您提供类似的解决方案。使用基于 walk-path 的Unix实用程序 jtc ,您可以通过遵循请求中的逻辑流并立即获得视觉反馈来解决此类问题你说对了。

让我告诉你(假设您的JSON位于file.json中)

1。您想要(递归)找到所有路径的第一件事。让我们按标签查找所有标签(使用lexeme <..>l:,量词:-表示“全部”):

bash $ <file.json jtc -rw'<path>l:'
[ "root" ]
[ "other1" ]
[ "other2" ]
bash $ 

2。现在,您要匹配数组中的"root"(假设您要非递归地进行此操作):

bash $ <file.json jtc -rw'<path>l: >root<'
"root"
bash $ 

3。一旦找到,您就想在JSON结构中将各个层/层向上耦合:

bash $ <file.json jtc -rw'<path>l: >root< [-2]'
{ "outputs": { "a": "b", "c": "d" }, "path": [ "root" ] }
bash $ 

4。从那一个您可以轻松解决所需的一个:

bash $ <file.json jtc -rw'<path>l:>root<[-2][outputs]'
{ "a": "b", "c": "d" }
bash $ 

-只需不到一分钟的时间就可以建立一个类似jtc 步行路径的概念:下标搜索词素

PS>披露:我是jtc-用于JSON操作的shell cli工具的创建者