Jsonnet是Google推出的一门为应用程序和工具开发人员提供的、基于Json的数据模板语言
安装
- Mac
brew install jsonnet- Go 安装
$ go install github.com/google/go-jsonnet/cmd/jsonnet@latest使用场景
jsonnet 主要是用做 Kubernetes、Prometheus、Grafana 等的配置管理
help
语法
注释
// 单行注释
/* 多行
注释 */简单运算
$ jsonnet -e '{key: 1+2}'
{
"key": 3
}self 引用
- self 关键字: 指向当前对象
$ cat << EOF >> t1.jsonnet
{
person1: {
name: "Alice",
welcome: "Hello " + self.name + "!",
},
person2: self.person1 { name: "Bob" },
}
EOF
$ jsonnet t1.jsonnet
{
"person1": {
"name": "Alice",
"welcome": "Hello Alice!"
},
"person2": {
"name": "Bob",
"welcome": "Hello Bob!"
}
}复杂运算
支持四则运算、条件语句、字符串拼接、字符串格式化、数据拼接、数据切片、python风格的lambda表达式
$ cat > t2.jsonnet << EOF
{
array: [1, 2] + [3],
math: (4 + 5) / 3 * 2,
format: 'Hello, I am %s' % 'alei',
concat: 'Hello, ' + 'I am alei',
slice: [1,2,3,4][1:3],
'list comprehension': [x * x for x in [1,2,3,4]],
condition:
if 2 > 1 then
'true'
else
'false',
}
EOF
$ jsonnet t2.jsonnet
{
"array": [
1,
2,
3
],
"concat": "Hello, I am alei",
"condition": "true",
"format": "Hello, I am alei",
"list comprehension": [
1,
4,
9,
16
],
"math": 6,
"slice": [
2,
3
]
}变量与引用
local关键字定义内部变量,通过变量名直接引用$指向根对象
$ cat > t3.jsonnet <<EOF
{
local name = 'aylei',
language:: 'jsonnet',
message: {
target: $.language,
author: name,
by: self.author,
}
}
EOF
$ jsonnet t3.jsonnet
{
"message": {
"author": "aylei",
"by": "aylei",
"target": "jsonnet"
}
}函数
- local 也可以定义函数,引用方式与变量相同,语法与 Python 类似
$ cat > t4.jsonnet << EOF
{
local hello(name) = 'hello %s' % name,
sum(x, y):: x + y,
newObj(name='alei', age=23, gender='male'):: {
name: name,
age: age,
gender: gender,
},
call_sum: $.sum(1, 2),
call_hello: hello('world'),
me: $.newObj(age=24),
}
EOF
$ jsonnet test.jsonnet
{
"call_hello": "hello world",
"call_sum": 3,
"me": {
"age": 24,
"gender": "male",
"name": "alei"
}
}面向对象
$ cat > t5.jsonnet << EOF
local base = {
f: 2,
g: self.f + 100,
};
base + {
f: 5,
old_f: super.f,
old_g: super.g,
}
EOF
$ jsonnet t5.jsonnet
{
"f": 5,
"g": 105,
"old_f": 2,
"old_g": 105
}- 更多示例请参考官方网站