Json 从嵌套元素(子元素)寻址父元素
我有以下的jsonnetJson 从嵌套元素(子元素)寻址父元素,json,jsonpath,jsonnet,Json,Jsonpath,Jsonnet,我有以下的jsonnet { local property = "global variable", property: "global property", bar: self.property, // global property baz: property, // global variable nested: { local property = "local
{
local property = "global variable",
property: "global property",
bar: self.property, // global property
baz: property, // global variable
nested: {
local property = "local variable",
property: "local property",
bar: self.property, // local property
baz: property, // local variable
// Q1:
// Can I get the property of parent from here? In my case:
// property: "global property"
// I want to use some kind of relative addressing, from child to parent not other way like:
// $.property
// I've tried:
// super.property
// but got errors
// Q2:
// Can I get the name of the key in which this block is wrapped? In my case:
// "nested"
}
}
我的目标是从子对象访问父对象。问题在评论中,以便更好地理解上下文。谢谢请注意,
super
用于对象继承(即,当您扩展基础对象以覆盖某些字段时,请参阅)
技巧是插入一个局部变量,该变量指向要引用的对象的self
:
{
local property = "global variable",
property: "global property",
bar: self.property, // global property
baz: property, // global variable
// "Plug" a local variable pointing here
local this = self,
nested: {
local property = "local variable",
property: "local property",
bar: self.property, // local property
baz: property, // local variable
// Use variable set at container obj
glo1: this.property,
// In this particular case, can also use '$' to refer to the root obj
glo2: $.property,
}
}
感谢您的回复。是否也可以获取包装此块的密钥的名称?hm不这样认为,没有看到任何反射/AST树检查支持,然后尝试通过
[keyname]
按构造使用“动态”密钥也是不可能的,因为这些“变量”密钥名必须“最终确定”到达对象本身(根据链接的示例),您可以执行类似于localfieldname=“foo”的操作;{[fieldname]:{something:fieldname}}
。局部必须在对象外部定义,因为构建对象时需要知道字段(并且对象内部的局部可以访问其内部,因此必须在使用之前构建对象)。不确定这会有多有用。有一些讨论是关于添加语法sugar以使在嵌套对象中使用字段名变得更好:。