jsonjolt

Unnest value/values from array


Source JSON:

[
  {
    "id": "1458720",
    "state": "CAMPAIGN_STATE_INACTIVE",
    "advObjectType": "VIDEO_BANNER",
    "dailyBudget": "97142857142",
    "placement": [
      "BANNER"
    ]
  },
  {
    "id": "3561353",
    "state": "CAMPAIGN_STATE_INACTIVE",
    "dailyBudget": "88142857452",
    "placement": []
  },
  {
    "id": "14353163",
    "state": "CAMPAIGN_STATE_RUNNING",
    "dailyBudget": "100000",
    "placement": [
      "PROFILE", "BANNER"
    ]
  }
]

Config:

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "*": "&", 
        "placement": {
          "0": "placement" 
        }
      }
    }
  }
]

I want to unnest placement array. And if there more than one element then separate them with comma.

Expected:

[
  {
    "id": "1458720",
    "state": "CAMPAIGN_STATE_INACTIVE",
    "advObjectType": "VIDEO_BANNER",
    "dailyBudget": "97142857142",
    "placement": "BANNER"
  },
  {
    "id": "3561353",
    "state": "CAMPAIGN_STATE_INACTIVE",
    "dailyBudget": "88142857452",
    "placement": null //or just without this key
  },
  {
    "id": "14353163",
    "state": "CAMPAIGN_STATE_RUNNING",
    "dailyBudget": "100000",
    "placement": "PROFILE, BANNER"
  }
]

Unlucky, I was able only to store first value in array after my config. And it also stores it as arrays, like:

{
  "id" : [ "1458720", "3561353", "14353163" ],
....
}
  1. How to reach expected output? If its not possible to separate values by comma, than at least first value from array.
  2. How can I get rid of arrays? I sometimes meet this task. I mean last example. How to get from
"id":["1458720", "3561353", "14353163"] -> [{"id": "1"}, {"id": "2"}, {"id": "3"}]

Solution

  • You can consecutively use these two specs

    [
      {// to get rid of the placement array if it has no element
        "operation": "shift",
        "spec": {
          "*": {
            "*": "[&1].&",
            "placement": { "*": "[&2].&1[]" }
          }
        }
      },
      {//to comma-separately concatenate the elements of the array 
        "operation": "modify-overwrite-beta",
        "spec": {
          "*": {
            "placement": "=join(',',@(1,&))"
          }
        }
      }
    ]