On This Page

Home / Stream/ Working With Data/ Transforming Data/Code Function Examples

Code Function Examples ​

The Code Function is a powerful way to transform events without needing to write a custom function. Using JavaScript methods such as map, reduce, forEach, some, and every is possible.

Cribl still recommends that you use Cribl Stream’s basic, built-in Functions, like Eval, as much as possible. But these use cases demonstrate some basic ways to use the new Code Function to solve questions asked in the Cribl’s Slack Community.

Basic Examples ​

Example Event Data ​

The first several examples below use the following JSON object as a sample event. You can copy and paste this event into Cribl Stream’s Sample Data pane. Add the Do Not Break Ruleset to your Source, select the noBreak1MB Event Breaker, and under your Source’s Advanced Settings, enable Parse JSON Event.

{
  "cpus": [
    {"number": 1, "name": "CPU1", "value": 2.3},
    {"number": 2, "name": "CPU2", "value": 3.1},
    {"number": 3, "name": "CPU3", "value": 5.1},
    {"number": 4, "name": "CPU4", "value": 1.3}
  ],
  "arch": "Intel x64"
}

Accessing Fields in an Event ​

To access a field inside an event, you can use the __e special variable. The __e prefix allows for access to the (context) event inside a JavaScript expression. For example, if you want to access the extracted field field-name, use the following syntax:

__e['field-name']

In other words, think of your code executing in a context like this:

function(__e: Event) {
 // your code here
}