bazaarvoice / jolt

JSON to JSON transformation library written in Java.
Apache License 2.0
1.55k stars 330 forks source link

Define additional value in array based on key #1243

Closed TheXplore2 closed 6 months ago

TheXplore2 commented 6 months ago

Hi, I need to transform the input:

{
  "id": "INC-199",
  "name": "Test Incident",
  "category": "SERVER"
}

to the following output:

{
  "cxid" : "INC-199",
  "cispec" : [ {
    "assetattrid": "CX_NAME",
    "alnvalue" : "Test Incident"
  }, {
    "assetattrid": "CX_CATEGORY",
    "alnvalue" : "SERVER"
  } ]
}

So far I have used this spec:

[
  {
    "operation": "shift",
    "spec": {
      "id": "cxid",
      "name": "cispec[].alnvalue",
      "category": "cispec[].alnvalue"
    }
  }
]

One important thing to keep in mind: Only the attributes name and category should end up in cispec. The rest of the json payload gets mapped normally.

I tried playing around with the operations default and modify-overwrite-beta, but I wasn't able to achieve what I am looking for. Thank you all for your time.

gbouget commented 6 months ago
[
  {
    "operation": "shift",
    "spec": {
      "id": "cxid",
      "name": {
        "#CX_NAME": "&1.@1.cispec.assetattrid", // indexing by &1 (name or category) before @1 in case the value is identical
        "@0": "&1.@1.cispec.alnvalue"
      },
      "category": {
        "#CX_CATEGORY": "&1.@1.cispec.assetattrid",
        "@0": "&1.@1.cispec.alnvalue"
      }
    }
  },
  {
    "operation": "shift",
    "spec": {
      "*": "&", // all attributes except name|category are mapped identically
      "name|category": {
        "*": {
          "*": "cispec[]" // to an array
        }
      }
    }
  }
]

image

TheXplore2 commented 6 months ago

Thank you so much, works like a charm.

Are there disadvantages to removing the value from the path, like this?

[
  {
    "operation": "shift",
    "spec": {
      "id": "cxid",
      "name": {
        "#CX_NAME": "&1.cispec.assetattrid", // indexing by &1 (name or category)
        "@0": "&1.cispec.alnvalue"
      },
      "category": {
        "#CX_CATEGORY": "&1.cispec.assetattrid",
        "@0": "&1.cispec.alnvalue"
      }
    }
  },
  {
    "operation": "shift",
    "spec": {
      "*": "&", // all attributes except name|category are mapped identically
      "name|category": {
        "*": "cispec[]" // to an array
      }
    }
  }
]
gbouget commented 6 months ago

I think it's great.

TheXplore2 commented 6 months ago

Perfekt, thanks. Have a great day :)