2015年10月31日土曜日

Go で JSON を Unmarshal する

JSON を構造体に変換する方法をメモ。
package main

import (
    "encoding/json"
    "fmt"
)

type Doc map[string]string

type DataStruct struct {
    Docs []Doc
}

type Response struct {
    Data DataStruct
}

func main() {
    byt := []byte(`
        {
          "data": {
            "docs": [
              {
                "key00": "val00",
                "key01": "val01"
              },
              {
                "key10": "val10",
                "key11": "val11"
              }
            ]
          }
        }
    `)

    res := &Response{}
    if err := json.Unmarshal(byt, res); err != nil {
        panic(err)
    }
    fmt.Println(res.Data.Docs[0]["key00"])
    fmt.Println(res.Data.Docs[1]["key10"])
}
$ go run main.go
val00
val10

package main

import (
    "encoding/json"
    "fmt"
)

type Track struct {
    Artist string `json:"artist"`
    Title  string `json:"title"`
}

type Picture struct {
    Id  int    `json:"id"`
    Url string `json:"url"`
}

type Attachment struct {
    Type    string `json:"type"`
    Track   `json:"track"`
    Picture `json:"picture"`
}

type Response struct {
    Id          int `json:"id"`
    FromId      int `json:"from_id"`
    Attachments []Attachment
}

func main() {
    byt := []byte(`
        {
          "id": 1,
          "from_id": 1111,
          "attachments": [
            {
              "type": "track",
              "track": {
                "artist": "Johann",
                "title": "Air on G String"
              }
            },
            {
              "type": "picture",
              "picture": {
                "id": 2222,
                "url": "http://example.com/public/picture.jpg"
              }
            }
          ]
        }
    `)
    response := &Response{}
    if err := json.Unmarshal(byt, response); err != nil {
        panic(err)
    }
    fmt.Println(response.Attachments[0].Track.Title)
    fmt.Println(response.Attachments[1].Picture.Url)
}
$ go run main.go
Air on G String
http://example.com/public/picture.jpg