LoginSignup
2
1

More than 5 years have passed since last update.

ruby-jsonnet使ってみた

Posted at

ruby-jsonnetを使ってみたので初歩的だけどまとめてみた(ライブラリのUsageがまだ書かれていないので)

そもそもJsonnetとはなんぞやという人はこちらをどうぞ(Jsonnetの薦め)

サンプルのJsonnetもここを参考にした。

インストール

ruby-jsonnet
を参考に、C++実装のオフィシャルライブラリとラッパーであるruby-jsonnetをインストール。

使い方

文字列から読み込み

jsonnet-sample1.rb
require 'jsonnet'
vm = Jsonnet::VM.new
print vm.evaluate(<<"EOS"
local base_id = 1;
[
  {
    id: base_id,
    name: "Alice",
  },
  {
    id: base_id+1,
    name: "Bob",
  },
]
EOS
)

次のような文字列のJSONが出力される

[
   {
      "id": 1,
      "name": "Alice"
   },
   {
      "id": 2,
      "name": "Bob"
   }
]

同様にJsonnetの中で関数を使いたい場合も

jsonnet-sample2.rb
require 'jsonnet'
vm = Jsonnet::VM.new
print vm.evaluate(<<"EOS"
local fibonacci(n) = if n <= 1 then 1
                     else fibonacci(n - 1) + fibonacci(n - 2);
local nodes = ["Node A", "Node B", "Node C"];
[
    {
        id: i,
        node: nodes[i],
        backoff: fibonacci(i+1)
    } for i in std.range(0, std.length(nodes)-1)
]
EOS
)

次のようなJSONが出力される

[
   {
      "backoff": 1,
      "id": 0,
      "node": "Node A"
   },
   {
      "backoff": 2,
      "id": 1,
      "node": "Node B"
   },
   {
      "backoff": 3,
      "id": 2,
      "node": "Node C"
   }
]

std.extVarを使いたい場合、あらかじめJsonnet::VMに値を渡す

jsonnet-sample3.rb
require 'jsonnet'
vm = Jsonnet::VM.new
vm.ext_var("foo", "bar")
print vm.evaluate('[std.extVar("foo")]')

出力

[
   "bar"
]

他は後で加筆すると思います。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1