skip to Main Content

If I have an array such as this one:

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

How can I convert this to an object that looks like the following?

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

I think I need to use reduce but I can’t quite figure out how to do it. I have tried a number of variations of this:

jq 'reduce .[] as $k (null; {($k: .})'

2

Answers


  1. Use setpath (manual) to set a given path to a value:

    reduce .[] as $k (null; setpath($k[:-1]; $k[-1]))
    
    {
      "AppA": {
        "ServiceA": {
          "SecretKey": "topSecretKeyA"
        }
      },
      "AppB": {
        "ServiceB": {
          "SecretKey": "topSecretKeyB"
        }
      },
      "AppC": {
        "ServiceC": {
          "SecretKey": "topSecretKeyC"
        }
      }
    }
    
    Login or Signup to reply.
  2. with map and from_entries

    map({key: .[0], value: {(.[1]): {(.[2]): .[3]}}}) | from_entries
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search