【Golang】Go言語でjsonを扱う

「Goプログラミング実践入門 標準ライブラリでゼロからWebアプリを作る」を読んでいたら、jsonを扱う項目があったので練習がてら自分でも書いてみました。

ほかにもやり方はあるようですが、まずはオーソドックスなやり方のencoding/json使ってやってみます。

ざっくり言うとこんな感じ。

  • Read
    • jsonの構造に沿って、Go側で構造体を作る。
    • json.Unmarshalで分解。
  • Write
    • 作りたいjsonの内容を構造体で書く。
    • json.MarshalIndentで読み込む。
    • ファイルに書きだす。

ソースコード

gistにあげてみました。

  • json_sample.jsonとjson_read_write.goをローカルに置いておきます。
  • プログラムを実行すると「03 program result」の結果が出力されて、json_output.jsonが作られます(はず!)。


Golangでjsonを扱う

Marshalについて

Marshalには2種類あって、json.Marsharlとjson.MarshalIndentがあるようです。

json.Marshal

https://golang.org/pkg/encoding/json/#Marshal
json.Marshalは単純にjson作るだけみたいです。やってみると下記のように1行で全部出力されました。

{"id":11111,"author":"toriyama akira","content":"","comment":{"comment_id":999999,"message":"sugeeeeeee"},"books":[{"book_id":1004,"title":"naushika"},{"book_id":2006,"title":"akira"},{"book_id":4005,"title":"inachu"}]}[

json.MarshalIndent

https://golang.org/pkg/encoding/json/#MarshalIndent
json.MarshalIndentはprefixとindentが指定できます。

func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error)

リンクの例の通りですが、こんな風に書くとこうなります。

output, err := json.MarshalIndent(&post_write, "<prefix>", "<indent>")
{
<prefix><indent>"id": 11111,
<prefix><indent>"author": "toriyama akira",
<prefix><indent>"content": "",
<prefix><indent>"comment": {
<prefix><indent><indent>"comment_id": 999999,
<prefix><indent><indent>"message": "sugeeeeeee"
<prefix><indent>},
<prefix><indent>"books": [
<prefix><indent><indent>{
<prefix><indent><indent><indent>"book_id": 1004,
<prefix><indent><indent><indent>"title": "naushika"
<prefix><indent><indent>},
<prefix><indent><indent>{
<prefix><indent><indent><indent>"book_id": 2006,
<prefix><indent><indent><indent>"title": "akira"
<prefix><indent><indent>},
<prefix><indent><indent>{
<prefix><indent><indent><indent>"book_id": 4005,
<prefix><indent><indent><indent>"title": "inachu"
<prefix><indent><indent>}
<prefix><indent>]
<prefix>}

つまづいたところ

構造体はあまり書いたことなかったんですね。
たぶん自分だけだと思いますが、しょーもないミスをしてました。

てきとーに書いて実行してたらいろいろエラーがでました。
こんな感じ

# command-line-arguments
./json_read_write.go:55:26: syntax error: unexpected newline, expecting comma or }
./json_read_write.go:60:23: syntax error: unexpected newline, expecting comma or }

Go言語の構造体って最後の要素にもカンマが必要なんですね!うっかりしてた。

        post_write := Post {
                Id : 11111,
                Author : "toriyama akira",
                Comment : Comment {
                        Comment_id : 999999,
                        Message : "sugeeeeeee",    // <----こことか!
                },
                Books : []Book {
                        Book {
                                Book_id : 1004,
                                Title : "naushika",   // <----こことか!
                        },
                        Book {
                                Book_id : 2006,
                                Title : "akira",    // <----こことか!
                        },
                        Book {
                                Book_id : 4005,
                                Title : "inachu",  // <----こことか!
                        },
                },       // <----こことか!
        }

コメント

他にもjson.NewEncoderでもできるみたい。後日調べてみよう。たぶん。

Goプログラミング実践入門 標準ライブラリでゼロからWebアプリを作る impress top gearシリーズ

Goプログラミング実践入門 標準ライブラリでゼロからWebアプリを作る impress top gearシリーズ

これはかなりいい本でした。
後日感想かかないとなあ。