1

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",
    ...
Ali
  • 1,759
  • 2
  • 32
  • 69

1 Answers1

2

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"])
}
jjo
  • 2,595
  • 1
  • 8
  • 16
  • 1
    Thanks for the solution. How can I refer to the entire "a: 'value for a', b: 'value for b' as a single object? The reason for that is this will be repeated across 100 properties so repeating the property name won't be a very convenient way of doing it for me. – Ali Nov 29 '19 at 04:02