jq のテンプレート機能で json を生成する

JSON パーサーの jq を JSON テンプレートエンジンとして利用しました。

github.com

テンプレートファイルでは、値を埋め込みたい場所に変数名を $varname のような形式で指定します。

// template.jq
{
  "metric": "metric.foo.bar",
  "timestamp": $timestamp,
  "value": 123.456789,
  "tags": {
    "device": $device,
    "feature": $feature
  }
}

標準入力を受け取らないので -n オプションを指定します。忘れやすい。

文字列になって欲しい変数は --arg で、余計な変換をしたくない変数は --argjson で指定します。

$ jq -n --argjson timestamp 1568082351 --arg device "80c3a1eb-aae9-4485-8ee8-24a7a4eec16a" --arg feature "collector" -f template.jq | tee 1.json
{
  "metric": "metric.foo.bar",
  "timestamp": 1568082351,
  "value": 123.456789,
  "tags": {
    "device": "80c3a1eb-aae9-4485-8ee8-24a7a4eec16a",
    "feature": "collector"
  }
}

数値文字列を --arg で指定すると自動的に文字列へ変換されてしまいます。

$ jq -n --arg timestamp 1568082351 --arg device "80c3a1eb-aae9-4485-8ee8-24a7a4eec16a" --arg feature "collector" -f template.jq | tee 2.json
{
  "metric": "metric.foo.bar",
  "timestamp": "1568082351",
  "value": 123.456789,
  "tags": {
    "device": "80c3a1eb-aae9-4485-8ee8-24a7a4eec16a",
    "feature": "collector"
  }
}

$ diff 1.json 2.json
3c3
<   "timestamp": 1568082351,
---
>   "timestamp": "1568082351",