shell 如何使用jq将字符串数组转换为对象?

cxfofazt  于 2023-05-01  发布在  Shell
关注(0)|答案(2)|浏览(169)

如果我有一个这样的数组:

[
  [
    "AppA",
    "ServiceA",
    "SecretKey",
    "topSecretKeyA"
  ],
  [
    "AppB",
    "ServiceB",
    "SecretKey",
    "topSecretKeyB"
  ],
  [
    "AppC",
    "ServiceC",
    "SecretKey",
    "topSecretKeyC"
  ]
]

如何将其转换为如下所示的对象?

{
  "AppA": {
    "ServiceA": {
      "SecretKey": "topSecretKeyA"
    }
  },
  "AppB": {
    "ServiceB": {
      "SecretKey": "topSecretKeyB"
    }
  },
  "AppC": {
    "ServiceC": {
      "SecretKey": "topSecretKeyC"
    }
  }
}

我想我需要使用reduce,但我不太清楚该怎么做。我已经尝试了一些变化:
jq 'reduce .[] as $k (null; {($k: .})'

m1m5dgzv

m1m5dgzv1#

使用setpath(手动)将给定路径设置为一个值:

reduce .[] as $k (null; setpath($k[:-1]; $k[-1]))
{
  "AppA": {
    "ServiceA": {
      "SecretKey": "topSecretKeyA"
    }
  },
  "AppB": {
    "ServiceB": {
      "SecretKey": "topSecretKeyB"
    }
  },
  "AppC": {
    "ServiceC": {
      "SecretKey": "topSecretKeyC"
    }
  }
}
gj3fmq9x

gj3fmq9x2#

使用mapfrom_entries

map({key: .[0], value: {(.[1]): {(.[2]): .[3]}}}) | from_entries

相关问题