Search code examples
jsonjolt

Duplicate JSON Objects into list of JSON Objects using JOLT


My Input JSON is as below:

[
  {
    "key1": "value1",
    "key2": "value2",
    "desc1": "test1",
    "desc2": "test2",
    "desc3": "test3"
  },
  {
    "key1": "value11",
    "key2": "value22",
    "desc1": "test11",
    "desc3": "test33"
  },
  {
    "key1": "value111",
    "key2": "value222",
    "desc2": null  
  }
]

I want to map "desc1", "desc2" and "desc3" to "desc" and copy/duplicate the the parent JSON object such that my output looks as below. Please note that desc1, desc2 and desc3 may be present or not present or the corresponding values can be null as well

[
  {
    "key1": "value1",
    "key2": "value2",
    "desc": "test1"
  },
  {
    "key1": "value1",
    "key2": "value2",
    "desc": "test2"
  },
  {
    "key1": "value1",
    "key2": "value2",
    "desc": "test3"
  },
  {
    "key1": "value11",
    "key2": "value22",
    "desc": "test11"
  },
  {
    "key1": "value11",
    "key2": "value22",
    "desc": "test33"
  },
  {
    "key1": "value111",
    "key2": "value222"
  }
]

Can anyone please let me know what specification should be used for this purpose. I tried various options present in this for but to no avail.


Solution

  • You should loop through each individual desc attributes such as

    [
      {
        "operation": "modify-overwrite-beta",
        "spec": {
          "*": {
            "~desc*": "NuLL" //set as literal "NuLL" whenever the value is null
          }
        }
      },
      {
        "operation": "shift",
        "spec": {
          "*": {
            "desc*": {
              "*": {//non-NuLL valued attributes 
                "@2": {//transferred from the level of "desc*"
                  "key*": "&4_&2.&",//attributes those start with "key"
                  "$1": "&4_&2.desc"//attributes those start with "desc"
                }
              },
              "NuLL": {//NuLL valued attributes 
                "@2": {
                  "key*": "&4_&2.&",
                  "": ""
                }
              }
            }
          }
        }
      },
      {//get rid of the object keys
        "operation": "shift",
        "spec": {
          "*": "[]"
        }
      }
    ]
    

    the demo on the site https://jolt-demo.appspot.com/ is :

    enter image description here