Search code examples
jsonjolt

How to get each element in a JSON array with JOLT


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.


Solution

  • 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"
          }
        }
      }
    ]