サンプルプログラム
package main
import (
"encoding/json"
"fmt"
)
type Book struct {
Id int `json:"id"`
Title string `json:"name"`
Categories []string `json:"categories"`
}
func main() {
book := new(Book)
book.Id = 1
book.Title = "title001"
book.Categories = []string{"category001", "category002", "category003"}
jsonBytes, _ := json.MarshalIndent(book, "", " ")
jsonStr := string(jsonBytes)
fmt.Println(jsonStr)
}
実行結果
{
"id": 1,
"name": "title001",
"categories": [
"category001",
"category002",
"category003"
]
}
package main
import (
"encoding/json"
"fmt"
)
func main() {
book := map[string]interface{}{
"id": 1,
"title": "title001",
"categories": []string{"category001", "category002", "category003"},
}
jsonBytes, _ := json.MarshalIndent(book, "", " ")
jsonStr := string(jsonBytes)
fmt.Println(jsonStr)
}
サンプルプログラム
package main
import (
"encoding/json"
"fmt"
)
type Book struct {
Id int `json:"id"`
Title string `json:"name"`
Categories []string `json:"categories"`
}
func main() {
str := "{\"id\":1,\"name\":\"title001\",\"categories\":[\"category001\",\"category002\",\"category003\"]}"
data := Book{}
json.Unmarshal([]byte(str), &data)
fmt.Printf("%+v", data)
}
実行結果
{Id:1 Title:title001 Categories:[category001 category002 category003]}
サンプルプログラム
package main
import (
"encoding/json"
"fmt"
)
func main() {
str := "{\"id\":1,\"name\":\"title001\",\"categories\":[\"category001\",\"category002\",\"category003\"]}"
var data map[string]interface{}
json.Unmarshal([]byte(str), &data)
fmt.Println(data["id"])
fmt.Println(data["categories"])
fmt.Println(data["categories"].([]interface{})[0])
}
実行結果
1
[category001 category002 category003]
category001