how to reference object properties and the object itself in Jsonnet

折月煮酒 提交于 2021-01-29 15:16:40

问题


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",
    ...

回答1:


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"])
}


来源:https://stackoverflow.com/questions/59097711/how-to-reference-object-properties-and-the-object-itself-in-jsonnet

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!