How to get each element in a JSON array with JOLT

32 Views Asked by At

I have this JSON:

{
  "CNPJ_PSSA_JUDC": "00000000",
  "NOME_PSSA_JUDC": "EMPRESA DE CNPJ 00000000 LTDA",
  "DOCT_SCIO": [
    "11111111111",
    "00000000000"
  ],
  "NOME_SCIO": [
    "PESSOA DE CPF 11111111111",
    "PESSOA DE CPF 00000000000"
  ],
  "DCRC_CRGO": [
    "Sócio",
    "Sócio-Administrador"
  ]
}

And I need this output with JOLT:

[
  {
    "CNPJ_PSSA_JUDC": "00000000",
    "NOME_PSSA_JUDC": "EMPRESA DE CNPJ 00000000 LTDA",
    "DOCT_SCIO": "11111111111",
    "NOME_SCIO": "PESSOA DE CPF 11111111111",
    "DCRC_CRGO": "Sócio"
  },
  {
    "CNPJ_PSSA_JUDC": "00000000",
    "NOME_PSSA_JUDC": "EMPRESA DE CNPJ 00000000 LTDA",
    "DOCT_SCIO": "00000000000",
    "NOME_SCIO": "PESSOA DE CPF 00000000000",
    "DCRC_CRGO": "Sócio-Administrador"
  }
]

My question is: how can I get each element of a JSON array with JOLT?

Every time I find myself facing the difficulty of traversing the array itself.

1

There are 1 best solutions below

2
Barbaros Özhan On BEST ANSWER

You can use the following transformation :

[
  { // nest non-arrays within a common object in order to use it 
    // within the next spec
    "operation": "shift",
    "spec": {
      "*PSSA_*": {
        "@": "&(1,2).&"
      },
      "*": "&"
    }
  },
  {
    "operation": "shift",
    "spec": {
      "*SCIO|DCRC_CRGO": {
        "*": {
          "@2,JUDC": { "*": "[&1].&" }, // go 2 levels up the tree to grab the values of the "JUDC" array
          "@": "[&1].&2"
        }
      }
    }
  },
  { // pick only one per each identical components of the arrays
    "operation": "cardinality",
    "spec": {
      "*": {
        "*": "ONE"
      }
    }
  }
]