json.Marshalとjson.Unmarshal

Go言語でJsonの扱いがわからなかったのでしらべてみた。

ざっくりと言えば、

json.Marshal

構造体からJSON文字列へ変換

json.Unmarshal

JSON文字列から構造体へ変換

package main

import (
    "encoding/json"
    "fmt"
)

type MessageMarshal struct {
        Name string
    Body string `json:"body_json"`
        Time int64
}

type MessageUnmarshal struct {
    Name string
    Body string
    Time int64
}

func main() {
    
    //Marshal
    mm := MessageMarshal{"Alice", "Hello", 1294706395881547000}
    b, _ := json.Marshal(mm)
    fmt.Println(string(b))
    
    //Unmarshal 
    c := []byte(`{"Name":"Alice","Body":"Hello","Time":1294706395881547000}`)
    var mu MessageUnmarshal
    json.Unmarshal(c, &mu)
    fmt.Println(mu.Name)
    fmt.Println(mu.Body)
    fmt.Println(mu.Time)
    
    //Interface
    var f interface{}
    json.Unmarshal(c, &f)
    fmt.Println(f)
    
}
{"Name":"Alice","body_json":"Hello","Time":1294706395881547000}
Alice
Hello
1294706395881547000
map[Name:Alice Body:Hello Time:1.294706395881547e+18]

JSON and Go - The Go Blog