【问题标题】:how to reference object properties and the object itself in Jsonnet如何在 Jsonnet 中引用对象属性和对象本身
【发布时间】:2019-11-29 01:18:04
【问题描述】:

我正在尝试在 Jsonnet 中构建一个类似于以下对象的对象,但我无法找到一种在 Jsonnet 中呈现它的方法。

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

基本上,我正在寻找一种方法来引用父对象中的以下部分:

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

【问题讨论】:

    标签: jsonnet


    【解决方案1】:

    iiuc 你的问题,下面的代码应该做到这一点——本质上使用一个变量,在这种情况下被称为p 来挂钩propertiesself

    第一个答案:单个嵌套字段:

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

    第二个答案:许多嵌套字段:

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

    【讨论】:

    • 感谢您的解决方案。我如何将整个“a:'a 的值,b:'b 的值'作为单个对象引用?原因是这将在 100 个属性中重复,因此重复属性名称不会是为我做这件事的非常方便的方式。
    猜你喜欢
    • 1970-01-01
    • 2016-05-14
    • 2021-03-28
    • 1970-01-01
    • 1970-01-01
    • 2016-10-09
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    相关资源
    最近更新 更多