如果JQ中存在对象则递归

时间:2019-08-29 11:40:11

标签: json edit jq

我具有以下结构:

{
    "hits": 
    [
        {
            "_index": "main"
        },
        {
            "_index": "main",
            "accordions": [
                {
                  "id": "1",
                  "accordionBody": "body1",
                  "accordionInnerButtonTexts": [
                    "button11",
                    "button12"
                  ]
                },
                {
                  "id": "2",
                  "accordionBody": "body2",
                  "accordionInnerButtonTexts": [
                    "button21",
                    "button22"
                    ]
                }
              ]
        }
    ]
}

我想进入这个结构:

{
    "index": "main"
}
{
    "index": "main",
    "accordions": 
    [
        {
            "id": "1",
            "accordionBody": "body1",
            "accordionInnerButtonTexts": [
                "button11",
                "button12"
             ]
         },
         {
             "id": "2",
             "accordionBody": "body2",
             "accordionInnerButtonTexts": [
                 "button21",
                 "button22"
             ]
         }
     ]
}

这意味着我始终希望将_index字段包含为index,并且要在对象中包含整个accordions列表(如果IT EXISTS存在)。这是我的尝试:

.hits[] | {index: ._index, accordions: recurse(.accordions[]?)}

它不能产生我想要的:

{
  "index": "main",
  "accordions": {
    "_index": "main"
  }
}
{
  "index": "main",
  "accordions": {
    "_index": "main",
    "accordions": [
      {
        "id": "1",
        "accordionBody": "body1",
        "accordionInnerButtonTexts": [
          "button11",
          "button12"
        ]
      },
      {
        "id": "2",
        "accordionBody": "body2",
        "accordionInnerButtonTexts": [
          "button21",
          "button22"
        ]
      }
    ]
  }
}
{
  "index": "main",
  "accordions": {
    "id": "1",
    "accordionBody": "body1",
    "accordionInnerButtonTexts": [
      "button11",
      "button12"
    ]
  }
}
{
  "index": "main",
  "accordions": {
    "id": "2",
    "accordionBody": "body2",
    "accordionInnerButtonTexts": [
      "button21",
      "button22"
    ]
  }
}

似乎创建了一个通过混合对象给出的所有不同排列的列表。这不是我想要的。正确的jq命令是什么,我的错误是什么?

1 个答案:

答案 0 :(得分:2)

所述问题不需要任何递归。使用您的尝试作为模型,实际上可以简单地写:

.hits[]
| {index: ._index} 
+ (if has("accordions") then {accordions} else {} end)

或者,具有完全不同的语义:

.hits[] | {index: ._index} + . | del(._index)