0

I try to flatten some JSON arrays using Jolt. I found how to do it on the first level, but I need to do it "recursively".

About the input:

  • the array I want to flatten are name "objects"
  • the inner objects all contain a "name" attribute but the others attributes are not common

Here is a simple sample:

{
    "objects": [
        {
            "name": "first",
            "type": "FIRST",
            "1st_attr": 0
        },
        {
            "name": "second",
            "type": "SECOND",
            "2nd_attr": 0
        }
    ],
    "sub": {
        "objects": [
            {
                "name": "third",
                "type": "THIRD",
                "3rd_attr": 0
            }
        ]
    }
}

Here is the output I want:

{
  "first" : {
    "1st_attr" : 0,
    "name" : "first",
    "type" : "FIRST"
  },
  "second" : {
    "2nd_attr" : 0,
    "name" : "second",
    "type" : "SECOND"
  },
  "sub" : {
    "third" : {
      "3rd_attr" : 0,
      "name" : "third",
      "type" : "THIRD"
    }
  }
}

The spec I have flatten the first level, but I would like to have it flatten every level (meanining, not just the second ;)...):

[
  {
    "operation": "shift",
    "spec": {
      "objects": {
        "*": {
          "@": "@(1,name)"
        }
      },
      "*": "&0"
    }
  }
]

Thanks for your help

GournaySylvain
  • 461
  • 1
  • 3
  • 16

1 Answers1

1

With Jolt you have to know where in your input the "object" arrays are. There isn't a way to "just find and flatten all the arrays, no matter where they are in the input doc".

Spec for the input and output you provided :

[
  {
    "operation": "shift",
    "spec": {
      "objects": {
        "*": "@(0,name)"
      },
      "sub": {
        "objects": {
          "*": "&2.@(0,name)"
        }
      }
    }
  }
]

Edit: added &2. to have sub.third instead of just third

SuperDJ
  • 7,488
  • 11
  • 40
  • 74
Milo S
  • 4,466
  • 1
  • 19
  • 22