jsonjolt

How to merge arrays and add key value as attribute in array items?


For the following input:

{
  "2024-10-10": {
    "item": [
      {
        "attr1": "a",
        "attr2": "b"
      },
      {
        "attr1": "c",
        "attr2": "d"
      }
    ]
  },
  "2025-10-10": {
    "item": [
      {
        "attr1": "e",
        "attr2": "f"
      }
    ]
  }
}

i'd like to get the output:

[
  {
    "attr1": "a",
    "attr2": "b",
    "date": "2024-10-10"
  },
  {
    "attr1": "c",
    "attr2": "d",
    "date": "2024-10-10"
  },
  {
    "attr1": "e",
    "attr2": "f",
    "date": "2025-10-10"
  }
]

For each object, the item array is merged, and new attribute date is added with the value from the top level. What Jolt transformation would work for this?


Solution

  • You can use the following shift transformation specs :

    [
      {
        "operation": "shift",
        "spec": {
          "*": { //the level of the objects with date keys
            "item": {
              "*": { //for the indexes of the item array
                "*": "&3_&1.&", //separate by date and the indexes of the item array 
                "$2": "&3_&1.date" //bring date values from 3 upper levels,
                                   //eg. indexed as 0,1,2(meaning $2)
              }
            }
          }
        }
      },
      { //get rid of the object keys
        "operation": "shift",
        "spec": {
          "*": "[]"
        }
      },
      { //sort alphabetically by the keys of the attributes
        "operation": "sort"
      }
    ]
    

    the demo on the site Jolt Transform Demo Using v0.1.1 is :

    enter image description here