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.

【Go】デコード、エンコードの実装例(marshal、unmarshal)

Posted at

はじめに

GoでAPIを作成する際などに、marshal、unmarshalがよく登場するので、使用例を簡単にまとめておきます。

使用例

main.go
package main

import (
	"encoding/json"
	"fmt"
)

// structの定義
type Person struct {
	Name  string `json:"name"`
	Age   int    `json:"age"`
	Email string `json:"email"`
}

func main() {
	// エンコードするデータ(Person型の変数)
	person := Person{
		Name:  "John",
		Age:   25,
		Email: "john@example.com",
	}

	// データをJSON形式にエンコード(marshal)
	jsonData, err := json.Marshal(person)
	if err != nil {
		fmt.Println("Error encoding JSON:", err)
		return
	}

	// エンコードされたJSONデータを表示
	fmt.Println("Encoded JSON Data:", string(jsonData))

	// エンコードされたJSONデータをデコード(unmarshal)
	var decodedPerson Person
	err = json.Unmarshal(jsonData, &decodedPerson)
	if err != nil {
		fmt.Println("Error decoding JSON:", err)
		return
	}

	// デコードされたデータを表示
	fmt.Println("Decoded Person:")
	fmt.Println("Name:", decodedPerson.Name)
	fmt.Println("Age:", decodedPerson.Age)
	fmt.Println("Email:", decodedPerson.Email)
}

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?