Search code examples
jsonjolt

Concat two JSON keys with manipulations


I've a JSON:

[
  {
    "taskId": 26,
    "adsName": "test name 5",
    "cityId": 2,
    "regionId": 46,
    "biddingPrice": 50,
    "limit": 140
  },
  {
    "taskId": 27,
    "adsName": "test name 6",
    "cityId": 5,
    "regionId": null,
    "biddingPrice": 60,
    "limit": 150
  },
  {
    "taskId": 28,
    "adsName": "test name 7",
    "cityId": null,
    "regionId": 224,
    "biddingPrice": 60,
    "limit": 150
  }
]

I want to concat cityId and regionId to one field cities. Order doesn't matter, but value from regionId should be always negative (with minus sign). So, from combination cityId = 2, regionId = 46 I expect `"cities": "2, -46", etc.

I expect:

[
  {
    "name": "test name 5",
    "all_limit": 140,
    "cities": "2, -46"
  },
  {
    "name": "test name 6",
    "all_limit": 150,
    "cities": "5"
  },
  {
    "name": "test name 7",
    "all_limit": 150,
    "cities": "-224"
  }
]

Solution

  • You can use the following transformation

    [
      {
        "operation": "modify-overwrite-beta",
        "spec": {
          "*": {
            "cts1": ["=notNull(@(1,cityId))", "=concat('-',@(1,regionId))"],
                  // prefix "regionId" values with "-" if "cityId"s are null
            "cts2": ["=isNull(@(1,cityId))", "=concat(', -',@(1,regionId))"],
                  // prefix "regionId" values with ", -" if "cityId"s are non-null
            "cities": "=concat(@(1,cts1),@(1,cts2))"
          }
        }
      },
      { // pick up the desired attributes while renaming them
        "operation": "shift",
        "spec": {
          "*": {
            "adsN*": "[#2].n&(0,1)",
            "limit": "[#2].all_&",
            // deliver them respectively by the upper nodes' indexes by using [#2] 
            // which traverses upwards by incrementing starts from 1
            "cities": {
              "*, -": { "$1": "[#4].&(1,1)" }, // cases in values ending with  ", -"
              "*": { "$1": "[#4].&1" } // others
            }
          }
        }
      },
      { // exchange the key-value pairs for the "cities" attribute
        "operation": "shift",
        "spec": {
          "*": {
            "all_limit|name": "[#2].&",
            "*": {
              "$": "[#3].@0"
            }
          }
        }
      }
    ]
    

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

    enter image description here