Ali
Ali

Reputation: 1879

how to reference object properties and the object itself in Jsonnet

I am trying to build an object like following in Jsonnet, but I couldn't work out a way to present it in Jsonnet.

"properties" :{
  "a" : "value for a",
  "b" : "value for b",
  ...
  "nested" : {
    "a" : "value for a",
    "b" : "value for b",
    ...
  }
}

Basically, I am looking for a way to refer to the following part in the parent object:

    "a" : "value for a",
    "b" : "value for b",
    ...

Upvotes: 1

Views: 1716

Answers (1)

jjo
jjo

Reputation: 3030

iiuc your question, below code should do it -- essentially use a variable, dubbed p in this case to hook properties's self:

1st answer: single nested field:

{
  properties: {
    local p = self,
    a: 'value for a',
    b: 'value for b',
    nested: {
      a: p.a,
      b: p.b,
    },
  },
}

2nd answer: many nested fields:

{
  // Also add entire `o` object as fields named from `field_arr`
  addNested(o, field_arr):: o {
    [x]: o for x in field_arr
  },
  base_properties:: {
    a: 'value for a',
    b: 'value for b',
  },
  // We can't "build" the object while looping on it to add fields,
  // so have it already finalized (`base_properties`) and use below
  // function to add the "nested" fields
  properties: $.addNested($.base_properties, ["n1", "n2", "n3"])
}

Upvotes: 2

Related Questions