JSON_ADD_ITEM

Use the JSON_ADD_ITEM script function to add an item to a JSON array or object document.

Syntax

JSON_ADD_ITEM (JSON, JSONPath, Value, [,Key,Cast]) or (JSON, JSONPath, Value, [index=-1],[Cast])

Parameters

  • JSON
    A string that is interpreted as a JSON document

  • JSONPath
    The JSONPath to the parent element of the inserted item. It has to point to a JSON array or a JSON object.
    Important!

    • If the object key already exists, its value will be overwritten with the new value. In the case of an array, the fourth parameter (key) denotes the array index under which the element is inserted (0 = first array item, -1 last array item)
    • You can not overwrite array values using JSON_ADD_ITEM. Use JSON_SET_VALUE for this purpose.

  • Value
    The value of the new item

  • Key [index=-1]
    If the parent element is an object, the key defines the object key under which the value is added. If the parent element is an array, the index defines the position of the array in which the value is added. Default = -1 (item is appended to the end of the array).

  • Cast
    (Optional) This parameter controls the conversion from Automic Script to JSON datatypes.

    • auto
      Automatic determination of datatype. AUTO tries to cast the given value to the following datatypes (in that order), the value will be converted to the first matching datatype: JSON String, Number or String.
    • boolean
      Converts the following values to JSON true or false:
      • true: 1
      • false: 0
    • number
      Force the conversion to a JSON number, even if Automic Script Datatype is not a number
    • String
      Force the casting to a string (NEW_VALUE might be another datatype)
    • JSON
      Interpret the string as a valid JSON document, for converting quoted JSON strings into JSON sub-documents.

Return value

None / Error Code in case of error

Runtime errors

The JSON_ADD_ITEM will fail with a runtime error on the following conditions:

  • 45334
    If your JSON document is invalid
  • 45344
    Invalid Parent Element: JSON object or array expected
  • 45343
    Invalid Array Index
  • 45349
    The Key parameter is required for adding a value to the JSON object
  • 45339
    JSONPath matches more than one element

Limitations

JSON documents larger than 1MB are not supported

Example

The following script adds a new owner key to the configuration object, and prepends the hdd02 entry in the bootSequence array with a new value:

:SET &JSON_DOC# = '[{"host":"192.168.0.10","active":false, "bootSequence":["hdd02"]}]'

:SET &RET# = JSON_ADD_ITEM(&JSON_DOC#, '$[0]', 'superadmin@automic.com','owner')

:SET &RET# = JSON_ADD_ITEM(&JSON_DOC#, '$[0].bootSequence', "ssd01",0)

:PRINT &JSON_DOC#

See also: