• Overview
  • Functions
    • Overview
    • action
    • connect
    • create_issue
    • create_vertex
    • dateprint
    • delete_vertex
    • disconnect
    • eject_issue
    • execute
    • find_timeseries
    • html_extract
    • if
    • javascript
    • log
    • query
    • read_timeseries
    • read_vertex
    • regex
    • sleep
    • split
    • stop_issue
    • suspend
    • suspend_until
    • update_vertex
    • write_timeseries
  • Definitions
  • Automation Issue Lifecycle
  • Automation Issue Lifecycle - Corner Cases
  • Hints for KI-Writers
  • HIRO 6 - Transition Guide for Users having used HIRO 5 before
  • Transition from KI Syntax 5

Definition

Use JavaScript expressions to assign values to variables.

HIRO contains a full JavaScript engine that can be used to manipulate data.

The JavaScript interpreter does not support the use of external 3rd party libraries.
Table 1. Technical Details

JavaScript Engine

Google V8 (Version 5.1.281.111)

Script Standard

ECMA-262 (Version 5)

Executed on

Engine Node

Usage

The JavaScript element allows processing data within a Knowledge Item. The final "result" returned by the element will be stored in the Variable specified in the StoreTo field.

If the JavaScript expression returns, for example, a list of filenames it will store this list as a single long value. You can use further processing of the output to store the results as separate values for each line/each entry in an array or a map of "Key:Value" pairs (see examples below).

exit: LOCAL::EXIT
result: LOCAL::RESULT = javascript("<js-script>")
Table 2. Arguments
Position Keyword Required Description

1

X

Script to be evaluated

Table 3. Return Values
Tag Description

result

Result of the script evaluation

exit

Numeric Exit-Code of the operation, 0 = success, 1 = failure

Example

Multiple return values

as separate values

You can use this functionality to write multiple return values as values into a variable by simply splitting your output.

For example: You return a list of filenames as single lines that is stored in the variable "result":

/opt/myfiles/abc.txt
/opt/myfiles/def.txt
/opt/myfiles/hij.txt

You would then split this output using the "newline separator" (\n) with the following JavaScript snippet:

result: LOCAL::OutputVariable = javascript("${result}.split('\n')")

This will split the contents of result after each "newline"-character (\n) and save it into separate values of "OutputVariable". You would then see something like this in your Issue:

"/OutputVariable": ["/opt/myfiles/abc.txt", "/opt/myfiles/def.txt", "/opt/myfiles/hij.txt"]

You can use CSV input by using "${result}".split(",") in your call in a similar way.

Convert to JSON map

If you require multiple return values, these can be encoded in a simple JSON map and afterwards be accessed by the JSON map accessor from a VarString:

result: OutputVariable = javascript('
  var result = {};
  result["ValueOne"] = new Date;
  result["ValueTwo"] = "this is just some string";
  JSON.stringify(result);
')

This way you end up with a JSON object looking like this:

  {"ValueOne":"Wed Dec 09 2015 14:11:45 GMT+0100 (CET)","ValueTwo":"this is just some string"}

Which you can then freely access by using VarString in the format ${VARIABLE#value_in_object} like in this example ${OutputVariable#ValueOne}. Please note that VarString only allows accessing the object directly, if you have a JSON structure that contains lists or other objects as values, you need to parse the structure to be able to easily access all elements.

Directly map Values and Keys

If you wish to set Values and their respective keys at the same time you need to directly map them. To do so you will use a JavaScript call to set a list of "Key:Value" pairs which then are stored as separate entries in a variable.

Here we store two values with different keys to the variable SampleMap.

result: SampleMap = javascript('
  var result = {};
  result["SomeKey"] = "SomeValue"
  result["2ndKey"] = "OtherValue"
  result
')

Note that we did not use a JSON.stringify() this time but actually return the map directly. This will create a data structure consisting of the specified variable containing "Key:Value" pairs as individual values and will look like this in the Issue:

{
  "/SampleMap": [
    {
      "value": "SomeValue",
      "key": "SomeKey"
    },
    {
      "value": "OtherValue",
      "key": "2ndKey"
    }
  ]
}

Parsing JSON data into variables

"Escaped characters" The JavaScript handling for HIRO automatically escapes special characters for Variables. This means JSON data in a variable will be "invalid" because of the escaped quotes (") to use JSON data stored this way you must use ''JSON.parse()'' to read the Variable and transform it back to "proper" JSON.

Here we have a simplified version of a Zendesk ticket in JSON (retrieved via API). We want to extract the description and store it in a variable to react further.

{
  "ticket": {
    "url": "https://itautopilot.zendesk.com/api/v2/tickets/2289.json",
    "id": 2289,
    "external_id": null,
    "via": {
      "channel": "web",
      "source": {
        "from": {},
        "to": {},
        "rel": null
      }
    },
    "created_at": "2016-01-14T13:19:35Z",
    "updated_at": "2016-01-14T14:03:34Z",
    "type": null,
    "subject": "Test Ticket - Please ignore and don't close",
    "raw_subject": "Test Ticket - Please ignore and don't close",
    "description": "Just testing some stuff.",
  }
}

We have already retrieved the JSON data and stored it in a variable ZendeskTicketJSON. We then parse the Variable into an object called obj. Then we access the value in the JSON structure.

obj = JSON.parse('${ZendeskTicketJSON}');
obj.ticket.description

This will return the value of "description" as a string and store it to the specified "StoreTo" Variable.

Caveats

HIRO uses Javascript to Script Standard ECMA Version 5. Make sure the elements you are trying to use are compatible with this script version. One example for a use case that was only implemented in ECMA v6 is the for …​ of loop statement.

The Javascript interpreter removes newlines from the source. This means that comments and certain instances where omitting semi-colons would not be an issue in a multi-line context, will break.

Here are some examples that will break, and how to resolve.

Single Line Comments

This will break:

var foo = "${LOCAL:VAR}"; // store to variable foo
foo.toLowerCase();

With SyntaxError "Unexpected End Of Input", to fix use a comment multi-line commen/ that self-closes.

var foo = "${LOCAL:VAR}"; /* store to variable foo */
foo.toLowerCase();

Omitting Semi-Colons

This will break:

var foo = "${LOCAL:VAR}"
var bar = "bar"
foo + bar

With SyntaxError "Unexpected token var", to fix always use semi-colons.

var foo = "${LOCAL:VAR}";
var bar = "bar";
foo + bar;

For Loop over Array values

ECMA does not support the for …​ of statement notation. This will not work:

var val;
var a = ["a", "b", "c"];

for (val of a) {
  val;
}

Instead, manually iterate and index to get the desired output:

var index;
var a = ["a", "b", "c"];
for (index = a.length - 1; index >= 0; --index) {
 a[index];
}