GoでJSONデータを使う

September 20, 2022

確認環境

$ go version
go version go1.15.5 darwin/amd64

JSONデータ -> struct に変換する

main.go

package main

import (
	"encoding/json"
	"fmt"
)

type Person struct {
	Name string `json:"name"`
	Age int `json:"age"`
}

func main() {
	tmpJson := `
	[
		{ "name": "Taro", "age": 20 },
		{ "name": "Jiro", "age": 50 }
	]`

	var unmarshalled []Person
	err := json.Unmarshal([]byte(tmpJson), &unmarshalled)
	if err != nil {
		fmt.Println("Error: ", err)
		return
	}

	fmt.Println("unmarshalled: ", unmarshalled)
}
$ go run main.go
unmarshalled:  [{Taro 20} {Jiro 50}]

struct -> JSONデータ に変換する

main.go

package main

import (
	"encoding/json"
	"fmt"
)

type Person struct {
	Name string `json:"name"`
	Age int `json:"age"`
}

func main() {
	var persons = []Person{
		{Name: "Taro", Age: 30},
		{Name: "Jiro", Age: 80},
	}

	myJson, err := json.MarshalIndent(persons, "", "    ")
	if err != nil {
		fmt.Println("Error: ", err)
	}
	fmt.Println(string(myJson))
}
$ go run main.go
[
    {
        "name": "Taro",
        "age": 30
    },
    {
        "name": "Jiro",
        "age": 80
    }
]

参考


SHARE

Profile picture

Written by tamesuu