#json #k8s #jsonnet
jsonnet -e <code>
jsonnet <file_name>
jsonnet -y <filename>
ファイルは配列でなければならない。例えば
// yaml_stream.jsonnet
local a = {
x: 1,
y: b.y,
};
local b = {
x: a.x,
y: 2,
};
[a, b]
これを jsonnet -y yaml_stream.jsonnet
すると
---
{
"x": 1,
"y": 2
}
---
{
"x": 1,
"y": 2
}
...
/* A C-style comment. */
# A Python-style comment.
{
cocktails: {
// Ingredient quantities are in fl oz.
'Tom Collins': {
ingredients: [
{ kind: "Farmer's Gin", qty: 1.5 },
{ kind: 'Lemon', qty: 1 },
{ kind: 'Simple Syrup', qty: 0.5 },
{ kind: 'Soda', qty: 2 },
{ kind: 'Angostura', qty: 'dash' },
],
garnish: 'Maraschino Cherry',
served: 'Tall',
description: |||
The Tom Collins is essentially gin and
lemonade. The bitters add complexity.
|||,
},
Manhattan: {
ingredients: [
{ kind: 'Rye', qty: 2.5 },
{ kind: 'Sweet Red Vermouth', qty: 1 },
{ kind: 'Angostura', qty: 'dash' },
],
garnish: 'Maraschino Cherry',
served: 'Straight Up',
description: @'A clear \ red drink.',
},
},
}
/*
- The local keyword defines a variable.
- Variables defined next to fields end with a comma (,).
- All other cases end with a semicolon (;).
*/
// A regular definition.
local house_rum = 'Banks Rum';
{
// A definition next to fields.
local pour = 1.5,
Daiquiri: {
ingredients: [
{ kind: house_rum, qty: pour },
{ kind: 'Lime', qty: 1 },
{ kind: 'Simple Syrup', qty: 0.5 },
],
served: 'Straight Up',
},
Mojito: {
ingredients: [
{
kind: 'Mint',
action: 'muddle',
qty: 6,
unit: 'leaves',
},
{ kind: house_rum, qty: pour },
{ kind: 'Lime', qty: 0.5 },
{ kind: 'Simple Syrup', qty: 0.5 },
{ kind: 'Soda', qty: 3 },
],
garnish: 'Lime wedge',
served: 'Over crushed ice',
},
}
/*
- self refers to the current object.
- $ refers to the outer-most object.
- ['foo'] looks up a field.
- .f can be used if the field name is an identifier.
- [10] looks up an array element.
- Arbitrarily long paths are allowed.
- Array slices like arr[10:20:2] are allowed, like in Python.
- Strings can be looked up / sliced too, by unicode codepoint.
*/
{
'Tom Collins': {
ingredients: [
{ kind: "Farmer's Gin", qty: 1.5 },
{ kind: 'Lemon', qty: 1 },
{ kind: 'Simple Syrup', qty: 0.5 },
{ kind: 'Soda', qty: 2 },
{ kind: 'Angostura', qty: 'dash' },
],
garnish: 'Maraschino Cherry',
served: 'Tall',
},
Martini: {
ingredients: [
{
// Use the same gin as the Tom Collins.
kind:
$['Tom Collins'].ingredients[0].kind,
qty: 2,
},
{ kind: 'Dry White Vermouth', qty: 1 },
],
garnish: 'Olive',
served: 'Straight Up',
},
// Create an alias.
'Gin Martini': self.Martini,
'Gin Fizz': self['Tom Collins']
}
{
concat_array: [1, 2, 3] + [4],
concat_string: '123' + 4,
equality1: 1 == '1',
equality2: [{}, { x: 3 - 1 }]
== [{}, { x: 2 }],
ex1: 1 + 2 * 3 / (4 + 5),
// Bitwise operations first cast to int.
ex2: self.ex1 | 3,
// Modulo operator.
ex3: self.ex1 % 2,
// Boolean logic
ex4: (4 > 3) && (1 <= 3) || false,
// Mixing objects together
obj: { a: 1, b: 2 } + { b: 3, c: 4 },
// Test if a field is in an object
obj_member: 'foo' in { foo: 1 },
// String formatting
str1: 'The value of self.ex2 is '
+ self.ex2 + '.',
str2: 'The value of self.ex2 is %g.'
% self.ex2,
str3: 'ex1=%0.2f, ex2=%0.2f'
% [self.ex1, self.ex2],
// By passing self, we allow ex1 and ex2 to
// be extracted internally.
str4: 'ex1=%(ex1)0.2f, ex2=%(ex2)0.2f'
% self,
// Do textual templating of entire files:
str5: |||
ex1=%(ex1)0.2f
ex2=%(ex2)0.2f
||| % self,
}
// Define a local function.
// Default arguments are like Python:
local my_function(x, y=10) = x + y;
local is_even(x) =
x % 2 == 0;
// Define a local multiline function.
local multiline_function(x) =
// One can nest locals.
local temp = x * 2;
// Every local ends with a semi-colon.
[temp, temp + 1];
local object = {
// A method
my_method(x): x * x,
};
{
eight_is_even: is_even(8),
// Functions are first class citizens.
call_inline_function:
(function(x) x * x)(5),
call_multiline_function: multiline_function(4),
// Using the variable fetches the function,
// the parens call the function.
call: my_function(2),
// Like python, parameters can be named at
// call time.
named_params: my_function(x=2),
// This allows changing their order
named_params2: my_function(y=3, x=2),
// object.my_method returns the function,
// which is then called like any other.
call_method1: object.my_method(3),
standard_lib:
std.join(' ', std.split('foo/bar', '/')),
len: [
std.length('hello'),
std.length([1, 2, 3]),
],
}
/*
Conditional expressions look like if b then e else e. The else branch is optional and defaults to null.
*/
local Mojito(virgin=false, large=false) = {
// A local next to fields ends with ','.
local factor = if large then 2 else 1,
// The ingredients are split into 3 arrays,
// the middle one is either length 1 or 0.
ingredients: [
{
kind: 'Mint',
action: 'muddle',
qty: 6 * factor,
unit: 'leaves',
},
] + (
if virgin then [] else [
{ kind: 'Banks', qty: 1.5 * factor },
]
) + [
{ kind: 'Lime', qty: 0.5 * factor },
{ kind: 'Simple Syrup', qty: 0.5 * factor },
{ kind: 'Soda', qty: 3 * factor },
],
// Returns null if not large.
garnish: if large then 'Lime wedge',
served: 'Over crushed ice',
};
{
Mojito: Mojito(),
'Virgin Mojito': Mojito(virgin=true),
'Large Mojito': Mojito(large=true),
'Large Virgin Mojeto': Mojito(large=true, virgin=true)
}
/* computed-field の中ではselfは使えない。 */
local Margarita(salted) = {
ingredients: [
{ kind: 'Tequila Blanco', qty: 2 },
{ kind: 'Lime', qty: 1 },
{ kind: 'Cointreau', qty: 1 },
],
[if salted then 'garnish']: 'Salt',
};
{
Margarita: Margarita(true),
'Margarita Unsalted': Margarita(false),
}
local arr = std.range(5, 8);
{
array_comprehensions: {
higher: [x + 3 for x in arr],
lower: [x - 3 for x in arr],
evens: [x for x in arr if x % 2 == 0],
odds: [x for x in arr if x % 2 == 1],
evens_and_odds: [
'%d-%d' % [x, y]
for x in arr
if x % 2 == 0
for y in arr
if y % 2 == 1
],
},
object_comprehensions: {
evens: {
['f' + x]: true
for x in arr
if x % 2 == 0
},
// Use object composition (+) to add in
// static fields:
mixture: {
f: 1,
g: 2,
} + {
[x]: 0
for x in ['a', 'b', 'c']
},
},
}
/*
- import するためのファイルは拡張子がlibsonnet
- importstr でテキストファイルをimportできる。
*/
local martinis = import 'martinis.libsonnet';
{
hoge: importstr 'garnish.txt',
'Vodka Martini': martinis['Vodka Martini'],
Manhattan: {
ingredients: [
{ kind: 'Rye', qty: 2.5 },
{ kind: 'Sweet Red Vermouth', qty: 1 },
{ kind: 'Angostura', qty: 'dash' },
],
garnish: importstr 'garnish.txt',
served: 'Straight Up',
},
}
// Extend above example to sanity check input.
local equal_parts(size, ingredients) =
local qty = size / std.length(ingredients);
// Check a pre-condition
if std.length(ingredients) == 0 then
error 'Empty ingredients.'
else [
{ kind: i, qty: qty }
for i in ingredients
];
local subtract(a, b) =
assert a > b : 'a must be bigger than b';
a - b;
assert std.isFunction(subtract);
{
test1: equal_parts(1, ['Whiskey']),
test2: subtract(10, 3),
object: {
assert self.f < self.g : 'wat',
f: 1,
g: 2,
},
assert std.isObject(self.object),
}
/*
jsonnet --ext-str prefix="Happy Hour " \
--ext-code brunch=true
*/
local lib = import 'library-ext.libsonnet';
{
[std.extVar('prefix') + 'Pina Colada']: {
ingredients: [
{ kind: 'Rum', qty: 3 },
{ kind: 'Pineapple Juice', qty: 6 },
{ kind: 'Coconut Cream', qty: 2 },
{ kind: 'Ice', qty: 12 },
],
garnish: 'Pineapple slice',
served: 'Frozen',
},
[if std.extVar('brunch') then
std.extVar('prefix') + 'Bloody Mary'
]: {
ingredients: [
{ kind: 'Vodka', qty: 1.5 },
{ kind: 'Tomato Juice', qty: 3 },
{ kind: 'Lemon Juice', qty: 1.5 },
{ kind: 'Worcestershire', qty: 0.25 },
{ kind: 'Tobasco Sauce', qty: 0.15 },
],
garnish: 'Celery salt & pepper',
served: 'Tall',
},
[std.extVar('prefix') + 'Mimosa']:
lib.Mimosa,
}
/*
jsonnet --tla-str prefix="Happy Hour" \
--tla-code brunch=true
tlaはfunction(){} と波括弧を使って利用することに注意。
*/
local lib = import 'library-tla.libsonnet';
// Here is the top-level function, note brunch
// now has a default value.
function(prefix, brunch=false) {
[prefix + 'Pina Colada']: {
ingredients: [
{ kind: 'Rum', qty: 3 },
{ kind: 'Pineapple Juice', qty: 6 },
{ kind: 'Coconut Cream', qty: 2 },
{ kind: 'Ice', qty: 12 },
],
garnish: 'Pineapple slice',
served: 'Frozen',
},
[if brunch then prefix + 'Bloody Mary']: {
ingredients: [
{ kind: 'Vodka', qty: 1.5 },
{ kind: 'Tomato Juice', qty: 3 },
{ kind: 'Lemon Juice', qty: 1.5 },
{ kind: 'Worcestershire', qty: 0.25 },
{ kind: 'Tobasco Sauce', qty: 0.15 },
],
garnish: 'Celery salt & pepper',
served: 'Tall',
},
[prefix + 'Mimosa']: lib.Mimosa(brunch),
}
/* 継承は + で行う。つまりobjectのmergeと同じ。
Base + {... } と書いてもいいし、+ を省略して
Base {
Derived
}
と書くこともできる。
*/
local Base = {
f: 2,
g: self.f + 100,
};
local WrapperBase = {
Base: Base,
};
{
Derived: Base + {
f: 5,
old_f: super.f,
old_g: super.g,
},
WrapperDerived: WrapperBase + {
Base+: { f: 4 },
},
}