A Deep-merge Function for Jsonnet


TL; DR: As of March 2025, there’s no deep merge function in Jsonnet’s standard library yet. So I wrote something myself.

  merge(obj1, obj2)::
    local all_fields = std.set(std.objectFields(obj1) + std.objectFields(obj2));
    {
      [f]: if !std.objectHas(obj1, f) then
        obj2[f]
      // no need to merge if the field only exist in 1 object
      else if !std.objectHas(obj2, f) then
        obj1[f]
      // deep merge recursively
      else if std.type(obj1[f]) == 'object' && std.type(obj2[f]) == 'object' then
        this.merge(obj1[f], obj2[f])
      // combine if they are arrays
      else if std.type(obj1[f]) == 'array' && std.type(obj2[f]) == 'array' then
        obj1[f] + obj2[f]
      // meaningless to combine if they're of different types or string, int or bool, etc.
      // value from obj2 will be used
      else
        obj2[f]
      for f in all_fields
    },

Not sure if I should do a PR to contribute but my last attempt was still there hanging 🙂