Golang にて JSON を扱う。エンコードしたり、デコードしたり

環境

  • Golang v1.25

Struct → JSON

package main

import (
	"encoding/json"
	"fmt"
)

func main() {

	type Test struct {
		ID int `json:"id"`
		Title string `json:"title"`
		OnSale bool `json:"onSale"`
	}

	test := Test{
		ID: 1,
		Title: "test",
		OnSale: true,
	}
	
	// []byte が返る
	b, err := json.Marshal(test)
	if err != nil {
		fmt.Printf("ERROR: %s\n", err.Error())
		return
	}
	// fmt.Printf("%s\n", b)でも可
	fmt.Print(string(b), "\n")//{"id":1,"title":"test","onSale":true}
}

byte型とは

type byte = uint8
byte is an alias for uint8 and is equivalent to uint8 in all ways. It is used, by convention, to distinguish byte values from 8-bit unsigned integer values.
uint8 is the set of all unsigned 8-bit integers. Range: 0 through 255.

[]byteは0から255の数字を扱うスライス。だと思う。
文字が数字になって格納されている。

文字列操作する時によく使う。
かもしれない。

b, _ := json.Marshal(test)

fmt.Print(b, "\n")
// [123 34 105 100 34 58 49 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 44 34 111 110 83 97 108 101 34 58 116 114 117 101 125]

fmt.Print(string(b), "\n")
//{"id":1,"title":"test","onSale":true}

// スライスなので for などで操作できる
for _, v := range b {
	fmt.Print(string(v), " -> ", v, "\n")
}

JSON → Struct

package main

import (
	"encoding/json"
	"fmt"
	"strings"
)

func main() {

	var test struct {
		ID int `json:"id"`
		Title string `json:"title"`
		OnSale bool `json:"onSale"`
	}

	j := `{"id":1,"title":"test","onSale":true}`

	doc := json.NewDecoder(strings.NewReader(j))
	doc.Decode(&test)
	fmt.Print(test, "\n")
}

Struct → JSON → Struct

ついでに var じゃなくて type バージョン。

package main

import (
	"encoding/json"
	"fmt"
	"strings"
)

func main() {

	type Test struct {
		ID int `json:"id"`
		Title string `json:"title"`
		OnSale bool `json:"onSale"`
	}

	test := Test{
		ID: 1,
		Title: "test",
		OnSale: true,
	}

	// エンコード
	b, _ := json.Marshal(test)

	// デコード
	res := Test{}
	doc := json.NewDecoder(strings.NewReader(string(b)))
	doc.Decode(&res)
	fmt.Print(res, "\n")
}
カテゴリー:Go