0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

json.Marshalの基礎理解

Posted at

構造体 → json → 構造体


package main

import (
	"encoding/json"
	"fmt"
)

// 横に`json:~`でjsonにした時のキーを記載
type Friend struct {
	Name string `json:"name_json"`
	Age  int    `json:"age_json"`
}

func main() {
	F := Friend{
		Name: "murama",
		Age:  44,
	}

	fmt.Println("F:  ", F)

	// 構造体からjsonへ
	j, err := json.Marshal(F)
	if err != nil {
		panic(err)
	}
	// string型に変換しないとbyte型で表示される。
	fmt.Println("j: ", j)
	fmt.Println("string(j): ", string(j))

	// 受皿となる空の構造体を作る。
	new_s := Friend{}
	fmt.Println("new_s: ", new_s)
	// 再び構造体へ
	err2 := json.Unmarshal(j, &new_s)
	if err2 != nil {
		panic(err2)
	}

	fmt.Println("new_s: ", new_s)

}



実行結果


F:   {murama 44}
j:  [123 34 110 97 109 101 95 106 115 111 110 34 58 34 109 117 
114 97 109 97 34 44 34 97 103 101 95 106 115 111 110 34 58 52 52 125]
string(j):  {"name_json":"murama","age_json":44}
new_s:  { 0}
new_s:  {murama 44}



0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?