json 使用reduce函数实现数组到对象的转换

mwkjh3gx  于 2022-12-20  发布在  其他
关注(0)|答案(1)|浏览(141)

我想从数组(从一个大json文件的另一个jq的输出)这样:

[
  {
    "Action": {
      "name1": {
        "product": {
          "summary": "Summary Product"
        }
      }
    }
  },
  {
    "Action": {
      "name2": {
        "gproduct": {
          "summary": "Summary Product"
        }
      }
    }
  },
  {
    "Action": {
      "name3": {
        "product1": {
          "summary": "Summary Product1"
        }
      }
    }
  },
  {
    "Action": {
      "name3": {
        "product2": {
          "summary": "Summary Product2"
        }
      }
    }
  }
]

获得:

{
  "Action": {
    "name1": {
      "product": {
        "summary": "Summary Product"
      }
    },
    "name2": {
      "gproduct": {
        "summary": "Summary Product"
      }
    },
    "name3": {
      "product1": {
        "summary": "Summary Product1"
      }
    },
    "name3": {
      "product2": {
        "summary": "Summary Product2"
      }
    }
  }
}

使用jq:reduce .[] as $o ({}; reduce ($o|keys)[] as $key (.; .[$key] += $o[$key] ))给出:

{
  "Action": {
    "name1": {
      "product": {
        "summary": "Summary Product"
      }
    },
    "name2": {
      "gproduct": {
        "summary": "Summary Product"
      }
    },
    "name3": {
      "product2": {
        "summary": "Summary Product2"
      }
    }
  }
}

在输出文件中,name3只与第二个产品一起列出,我希望所有产品都单独列出。如果nameX下有多个产品,则结果只列出最后一个产品。

ykejflvf

ykejflvf1#

可以使用乘法运算符进行递归合并。

reduce .[] as $obj ({}; . * $obj)

Online demo

相关问题