Search code examples
jsonnet

How to use std.prune() with a function?


I have a function that takes one required parameter and two optional parameters. I want the function to prune out the optional parameters from the result if they are not provided, but it evaluates to an empty expression.

My function:

local newTaskParam(pName, pDesc=null, pDef=null) = {
    local param = std.prune(
        {
            name: pName,
            description: pDesc,
            default: pDef,
        },
    )
};
{
    test: newTaskParam("pipeline-debug"),
}

Current Output:

{
   "test": { }
}

Expected output:

{
   "test": {
      "name": "pipeline-debug"
   }
}

Solution

  • The issue is that you are returning an empty object with:

    local func() = {
      // expected here to return field: value pairs
    };
    

    For your purpose, the easiest way should be returning the result of calling std.prune() without "building" the returned object yourself:

    local func() = std.prune(
    );
    

    Thus, you could implement it as:

    local newTaskParam(pName, pDesc=null, pDef=null) = std.prune(
      {
        name: pName,
        description: pDesc,
        default: pDef,
      }
    );
    {
      test: newTaskParam('pipeline-debug'),
    }