1. Qiita
  2. 投稿
  3. Go

GoでJSONとYAMLを相互変換するツールを作った

  • 21
    いいね
  • 0
    コメント

表題の通りですが

Golangの習作です!!!

バイナリもあるよ

無駄にマルチプラットフォーム。無駄なkusocommitで Travis CI さんの貴重なリソースを浪費してしまい申し訳ない :sob:

つかいかた

$PATH の通ったところにポイーすればインストール完了です。

小機能なので readmej2y --help を読めばすぐ分かると思います!

JSONをYAMLに変換

JSON Tutorial からサンプルJSONを拝借。

$ cat example.json
{"employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]}
$ j2y example.json
employees:
- firstName: John
  lastName: Doe
- firstName: Anna
  lastName: Smith
- firstName: Peter
  lastName: Jones

ファイルに出力

$ j2y -o example.yml example.json
$ cat example.yml
employees:
- firstName: John
  lastName: Doe
- firstName: Anna
  lastName: Smith
- firstName: Peter
  lastName: Jones

YAMLからJSONに変換

$ j2y -r example.yml
{
  "employees": [
    {
      "firstName": "John",
      "lastName": "Doe"
    },
    {
      "firstName": "Anna",
      "lastName": "Smith"
    },
    {
      "firstName": "Peter",
      "lastName": "Jones"
    }
  ]
}

YAMLからJSONに変換(JSONを1行出力)

$ j2y -r -m example.yml
{"employees":[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]}

引数に直接入力文字列を書く

$ j2y -e '{"employees":[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]}'
employees:
- firstName: John
  lastName: Doe
- firstName: Anna
  lastName: Smith
- firstName: Peter
  lastName: Jones

標準入力を渡す

$ echo '{"employees":[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]}' | j2y
employees:
- firstName: John
  lastName: Doe
- firstName: Anna
  lastName: Smith
- firstName: Peter
  lastName: Jones

感想

ほとんど神パッケージ2つをくっつけただけの他力本願寺ツールでした。

Comments Loading...