Search code examples
jsonjsonata

How to append an array nested inside JSON object using JSONata


I'm trying to use JSONata to append an extra object within the "options" array in the following JSON:

{
  "description": "[IGNORE] Field used for testing",
  "displayOrder": 2,
  "fieldType": "select",
  "formField": true,
  "groupName": "excell_data",
  "label": "Dev Test Field [IGNORE]",
  "name": "dev_test_field",
  "options": [
    {
      "description": "Choice number one",
      "displayOrder": 1,
      "hidden": false,
      "label": "Option 1",
      "value": "1"
    },
    {
      "description": "Choice number two",
      "displayOrder": 2,
      "hidden": false,
      "label": "Option 2",
      "value": "2"
    },
    {
      "description": "Choice option three",
      "displayOrder": 3,
      "hidden": false,
      "label": "Option 3",
      "value": "3"
    }
  ],
  "type": "enumeration"
}

So that it becomes:

{
  "description": "[IGNORE] Field used for testing",
  "displayOrder": 2,
  "fieldType": "select",
  "formField": true,
  "groupName": "excell_data",
  "label": "Dev Test Field [IGNORE]",
  "name": "dev_test_field",
  "options": [
    {
      "description": "Choice number one",
      "displayOrder": 1,
      "hidden": false,
      "label": "Option 1",
      "value": "1"
    },
    {
      "description": "Choice number two",
      "displayOrder": 2,
      "hidden": false,
      "label": "Option 2",
      "value": "2"
    },
    {
      "description": "Choice option three",
      "displayOrder": 3,
      "hidden": false,
      "label": "Option 3",
      "value": "3"
    },
    {
      "description": "Choice number four",
      "displayOrder": 4,
      "hidden": false,
      "label": "Option 4",
      "value": 4
    }
  ],
  "type": "enumeration"
}

However when I try to use the append function, I am struggling to return the parent JSON along with the appended object nested within.

JSONata fiddler link here: https://try.jsonata.org/iv7zhPZcr

Could anyone shed light on where I'm going wrong?

Many thanks in advance. Jonathan


Solution

  • Use the transform operator to modify the options object in the parent object:

    $ ~> | $ | {
        "options": [options, {
            "description": "Choice number four",
            "displayOrder": 4,
            "hidden": false,
            "label": "Option 4",
            "value": 4
        }]
    } | 
    

    See: https://try.jsonata.org/9RLURkd9l

    https://docs.jsonata.org/other-operators#-------transform