Introduction

Did you know eval has a full set of JSON manipulation functions?

Eval allows you to read, iterate over, and create JSON values in-pipeline. This makes doing things like constructing payloads for integrations with other tools simple, and you can do it all in eval.

Example: fruit!

Let’s look at a simple example. Consider the following JSON data:

{
    "fruit": {
        "apples": 5,
        "oranges": 10,
        "pears": 2512315,
        "lemons": 1
    }
}

Say this data was ingested into the tag fruit, and we want to get a total count of all of the fruit we have. The json extraction module won’t work here because there’s no way to extract all the key names if we don’t know which keys exist. Eval to the rescue!

I’ll post the entire query here, and then break it down:

tag=fruit json fruit
| eval

fruits = json_keys(fruit);
total = 0;

for (i=0; i<len(fruits); i++) {
    value = json_get(fruit, fruits[i]);
    total = total + int(value);
}
| table fruit total

Keys

fruits = json_keys(fruit);

The first line transforms the JSON object into an array of key names (in this example we’ll get [apples oranges pears lemons]). By using the json_keys() built-in to get an array, we can then use a for loop to iterate over all of the keys, without having to know their names a priori.

Loop and get

for (i=0; i<len(fruits); i++) {
    value = json_get(fruit, fruits[i]);
    total = total + int(value);
}

The next part is simple – for each index of our array, call the json_get() function to retrieve the value of the given key from the JSON object, and then add it to our running total.

Output

| table fruit total

fruit

Success!