Search code examples
jsonjolt

JOLT add property based on name of another property


I've two types of JSONs :

First one :

[
  {
    "type": "link",
    "link": {
      "url": "https://google.com",
      "photo": {
        "id": 457467865,
        "owner_id": 2000016837,
        "sizes": [
          {
            "height": 89,
            "type": "a",
            "width": 200,
            "url": "https://sun9-41.userapi.com/LE7UgRqqunque4uSl2YxmK029tgImcFYHjpg"
          }
        ]
      },
      "title": "Test"
    }
  }
]

Second one :

[
  {
    "type": "link",
    "link": {
      "url": "amazon.com",
      "video": {
        "date": 1674803349,
        "duration": 30,
        "image": [
          {
            "url": "https://i.mycdn.me/getVideoPreview?id=3679686756942&idx=0&type=39&tkn=bKnXfn=vid_s",
            "width": 130,
            "height": 96,
            "with_padding": 1
          }
        ],
        "id": 456249970,
        "owner_id": -18098621
      },
      "title": "Test"
    }
  }
]

I want to grab link.url param and link.title. It's common for both JSONs. Also I want to grab id and owner_id from photo or video object and concat values to new property called media_id. Also I want to add new property called media_type based on JSON object name (photo or video). So I expect this result (for example for second example):

{
  "owner_id" : -18098621,
  "title" : "Test",
  "url" : "amazon.com",
  "media_id" : "-18098621_456249970",
  "media_type": "video"
}

I tried with it:

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "link": {
          "photo|video": {
            "id": "id",
            "owner_id": "owner_id"
          },
          "title": "title",
          "url": "url"
        }
      }
    }
  },
  {
    "operation": "modify-overwrite-beta",
    "spec": {
      "media_id": "=concat(@(1,owner_id),'_',@(1,id))"
    }
  }
]

But how can I add media_type which I described above?


Solution

  • You can use $ wildcard within the related objects as shortening the current transformation such as

    [
      {
        "operation": "shift",
        "spec": {
          "*": {
            "link": {
              "photo|video": {
                "id|owner_id": "&",
                "$": "media_type"
              },
              "title|url": "&"
            }
          }
        }
      },
      {
        "operation": "modify-overwrite-beta",
        "spec": {
          "media_id": "=concat(@(1,owner_id),'_',@(1,id))"
        }
      }
    ]