JOLT: Joining two arrays based on field values

28 Views Asked by At

This is my incoming JSON. I want to transform it using JOLT library:

{
    "body": {
        "authors": [
        {
            "ID": 1,
            "name": "Hans",
            "timeStamp": "2020-01-01T00:57:36+00:00"
        },
        {
            "ID": 2,
            "name": "Peter",
            "timeStamp": "2020-01-01T01:00:15+00:00"
        }
        ],
        "releases": {
        "bookdata": [
            {
            "bookname": "bla",
            "authorID": 1
            },
            {
            "bookname": "blub",
            "authorID": 2
            }
        ]
        }
    }
}

I want to reach the following JSON structure. The ID of the authors array should be matched and the fields of the respective array should be merged into the bookdata array.

{
    "body": {
        "releases": {
        "bookdata": [
            {
            "bookname": "bla",
            "authorName": "Hans",
            "authorTimeStamp": "2020-01-01T00:57:36+00:00"
            },
            {
            "bookname": "blub",
            "authorName": "Peter",
            "authorTimeStamp": "2020-01-01T01:00:15+00:00"
            }
        ]
        }
    }
}
1

There are 1 best solutions below

0
Barbaros Özhan On

You can use the following transformation :

[
  { // make values, those to be matched, object keys
    "operation": "shift",
    "spec": {
      "body": {
        "authors": {
          "*": {
            "*": "@1,ID.&"
          }
        },
        "releases": {
          "bookdata": {
            "*": {
              "*": "@1,authorID.&"
            }
          }
        }
      }
    }
  },
  {
    "operation": "shift",
    "spec": {
      "*": {
        "ID": { // check out the existence of the attribute "ID"
          "@1,authorID": { // check out the existence of the attribute "authorID"
            "@2": "[]" // replicate whole object from 2 levels upper
          }
        }
      }
    }
  },
  { // leave the desired attributes only
    "operation": "remove",
    "spec": {
      "*": {
        "*D": ""
      }
    }
  }
]

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

enter image description here