Search code examples
jsonnet

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?


Solution

  • 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.