我在一个jsonnet文档中有一个配置文件列表
main.jsonnet
,如下所示:
local configFiles = [
import "file1.jsonnet",
import "file2.jsonnet",
import "file3.jsonnet",
];
{
# ...something goes here...
}
导入的文件包含任意的密钥集(也就是说,我们事先不知道密钥的完整列表)。对于这个例子,
file1.jsonnet
看起来像:
{
names: ["alice", "bob"],
colors: ["red"],
}
file2.jsonnet
看起来像:
{
names: ['mallory'],
animals: ['cow'],
}
和
file3.jsonnet
看起来像:
{
names: ['angus'],
colors: ['brown'],
animals: ['horse'],
size: ['medium'],
}
我想替换
# ...something goes here...
使用适当的代码生成:
{
names: ["alice", "bob", "mallory", "angus"],
colors: ["red", "brown"],
animals: ["cow", "horse"],
size: ["medium"],
}
这将是一个简单的迭代解决方案很容易;在Python中,我可能会写以下内容:
import _jsonnet as jsonnet
import json
merged = {}
fileNames = ["file1.jsonnet", "file2.jsonnet", "file3.jsonnet"]
configFiles = [json.loads(jsonnet.evaluate_file(fn)) for fn in fileNames]
for configFile in configFiles:
for k, v in configFile.items():
merged[k] = merged.get(k, []) + v
print(json.dumps(merged, indent=2))
逻辑看起来很简单,但jsonnet中唯一可用的迭代器是数组和对象的理解,这似乎更棘手。我试过了:
{
[k]: if self[k] then self[k] + configFile[k] else configFile[k]
for configFile in configFiles
for k in std.objectFields(configFile)
}
但结果是:
RUNTIME ERROR: duplicate field name: "names"
main.jsonnet:(7:1)-(11:2)