Deepak Deore
Deepak Deore

Reputation: 332

jsonnet - remove null values from array

I want to remove empty values and duplicates from an array, duplicate values are getting removed, empty isn't

template:

local sub = [ "", "one", "two", "two", ""];
{
 env: std.prune(std.uniq(std.sort(sub)))
}

output:

{
  "env": [
    "",
    "one",
    "two"
  ]
}

std.prune is supposed to remove empty, null but it is not happening, am I doing something wrong? or is there other way to remove empty values?

Upvotes: 1

Views: 4058

Answers (2)

Behe
Behe

Reputation: 7940

You can use std.filter(func,arr) to keep only non empty entries.

std.filter(func, arr)

Return a new array containing all the elements of arr for which the func >function returns true.

You can specify the first parameter to std.filter as a function that takes a single parameter and returns true, if the parameter is not "". The second parameter is your array.

local nonEmpty(x)= x != "";
local sub = [ "", "one", "two", "two", ""];
{
   env: std.uniq(std.filter(nonEmpty,sub))
}

You can also define it inline:

local sub = [ "", "one", "two", "two", ""];
{
   env: std.uniq(std.filter(function(x) x != "",sub))
}

This removes empty values from the array and yields:

> bin/jsonnet fuu.jsonnet 
{
   "env": [
      "one",
      "two"
   ]
}

Upvotes: 2

jjo
jjo

Reputation: 3020

As per https://jsonnet.org/ref/stdlib.html#prune

"Empty" is defined as zero length arrays, zero length objects, or null values.

i.e. "" is not considered for pruning, you can then use a comprehension as (note also using std.set() as it's literally uniq(sort())):

local sub = [ "", "one", "two", "two", ""];
{
   env: [x for x in std.set(sub) if x!= ""]
}

or std.length(x) > 0 for that conditional.

Upvotes: 3

Related Questions