JOLT - Combine arrays and add in attribute of parent key

Viewed 183

I'm trying to design a JOLT script to combine two arrays and add in the parent key as an attribute to the items.

So I have this input JSON:

{
  "userData": {
    "entities": [
      {
        "username": "test1",
        "address": "exampleAddress"
      },
      {
        "username": "test2",
        "address": "exampleAddress2"
      }
    ]
  },
  "programData": {
    "entities": [
      {
        "crashed?": "no",
        "time ran?": "N/A"
      },
      {
        "crashed?": "yes",
        "time ran?": "5 min"
      }
    ]
  }
}

And wrote this JOLT which merges the arrays into one:

[
  {
    "operation": "shift",
    "spec": {
      "userData": {
        "entities": {
          "*": "[]"
        }
      },
      "programData": {
        "entities": {
          "*": "[]"
        }
      }
    }
  }
]

Which gives me this output:

[
  {
    "username": "test1",
    "address": "exampleAddress"
  },
  {
    "username": "test2",
    "address": "exampleAddress2"
  },
  [
    {
      "crashed?": "no",
      "time ran?": "N/A"
    },
    {
      "crashed?": "yes",
      "time ran?": "5 min"
    }
  ]
]

However, I'd like to add in the parent name as a tag in the child array items, like this desired JSON:

[
  {
    "parent": "userData",
    "username": "test1",
    "address": "exampleAddress"
  },
  {
    "parent": "userData",
    "username": "test2",
    "address": "exampleAddress2"
  },
  [
    {
      "parent": "programData",
      "crashed?": "no",
      "time ran?": "N/A"
    },
    {
      "parent": "programData",
      "crashed?": "yes",
      "time ran?": "5 min"
    }
  ]
]

Any help would be much appreciated!

EDIT: I've learned I can use the command "&2" to get a value two indexes up the chain, but do not know how to get that value into the array values.

1 Answers

You need to pick the outermost key names ("userData" and "programData") while combining them under the index of sub-elements of "entities" array. You can manage this by the following specs

[
  //combine all key-value pairs under common objects
  {
    "operation": "shift",
    "spec": {
      "*": {
        "*": {
          "*": {
            "$2": "&.[&1].parent",
            "*": "&3.[&1].&"
          }
        }
      }
    }
  },
  //get rid the outermost key names
  {
    "operation": "shift",
    "spec": {
      "*": ""
    }
  }
]

enter image description here

Related