yjっていうコマンド名多すぎ問題がある気がしますが、YAML, TOML, JSON, HCLの相互変換をしてくれるツールの紹介です。
tomlを使う必要があったのですが、いまいち形式になれてないのでjsonで見たいと思い探していました。
プルリクとissueが溜まっている感は少しあるので、別のコマンドを探すのが良いかもしれません。
インストール方法
brewとかで配布されているわけではないので、素直にgo getします。
$go get github.com/sclevine/yj
使い方
$yj --helpとすると雰囲気がつかめます
$ yj --help Usage: yj [-][ytjcrneikh] Convert between YAML, TOML, JSON, and HCL. -x[x] Convert using stdin. Valid options: -yj, -y = YAML to JSON (default) -yy = YAML to YAML -yt = YAML to TOML -yc = YAML to HCL -tj, -t = TOML to JSON -ty = TOML to YAML -tt = TOML to TOML -tc = TOML to HCL -jj = JSON to JSON -jy, -r = JSON to YAML -jt = JSON to TOML -jc = JSON to HCL -cy = HCL to YAML -ct = HCL to TOML -cj, -c = HCL to JSON -cc = HCL to HCL -n Do not covert inf, -inf, and NaN to/from strings (YAML in/out only) -e Escape HTML (JSON out only) -i Indent output (JSON or TOML out only) -k Attempt to parse keys as objects or numbers types (YAML out only) -h Show this help message Error: invalid flags specified: l p
特筆すべきはこのコマンドは入力を標準入力で受け取ります。
つまり yj hoge.yml みたいにはできません。
この点を踏まえて実際に使ってみます。今回はtoml -> jsonを試してみます。
例題として使うtomlはこのサンプルです。
https://github.com/toml-lang/toml/blob/master/tests/example.toml
さてこれをsample.tomlで保存し、リダイレクトを使って実行します。
$ yj -tj < example.toml
{"clients":{"data":[["gamma","delta"],[1,2]],"hosts":["alpha","omega"]},"database":{"connection_max":5000,"enabled":true,"ports":[8001,8001,8002],"server":"192.168.1.1"},"owner":{"bio":"GitHub Cofounder & CEO\nLikes tater tots and beer.","dob":"1979-05-27T07:32:00Z","name":"Tom Preston-Werner","organization":"GitHub"},"products":[{"name":"Hammer","sku":738594937},{"color":"gray","name":"Nail","sku":284758393}],"servers":{"alpha":{"dc":"eqdc10","ip":"10.0.0.1"},"beta":{"country":"中国","dc":"eqdc10","ip":"10.0.0.2"}},"title":"TOML Example"}
いい感じですね。 さらにjq をパイプでつなげると見やすくなります。
$yj -tj < example.toml | jq .
{
"clients": {
"data": [
[
"gamma",
"delta"
],
[
1,
2
]
],
"hosts": [
"alpha",
"omega"
]
},
"database": {
"connection_max": 5000,
"enabled": true,
"ports": [
8001,
8001,
8002
],
"server": "192.168.1.1"
},
"owner": {
"bio": "GitHub Cofounder & CEO\nLikes tater tots and beer.",
"dob": "1979-05-27T07:32:00Z",
"name": "Tom Preston-Werner",
"organization": "GitHub"
},
"products": [
{
"name": "Hammer",
"sku": 738594937
},
{
"color": "gray",
"name": "Nail",
"sku": 284758393
}
],
"servers": {
"alpha": {
"dc": "eqdc10",
"ip": "10.0.0.1"
},
"beta": {
"country": "中国",
"dc": "eqdc10",
"ip": "10.0.0.2"
}
},
"title": "TOML Example"
}