1
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 3 years have passed since last update.

Golangで構造体に構造体を入れて、複雑なJsonを出力する

Posted at

変数名とか適当です。

Kouzou_oyaの中にはKouzou_kobunというキーがあり、
変数の型がKouzou1という構造体になってる感じです。(事前にこういう定義をしないと行けないのがGo言語特有な気がします)

main.go
package main

import (
	"encoding/json"
	"fmt"
)

type Kouzou1 struct {
	Var1 string
	Var2 int
}

type Kouzou_oya struct {
	Status       string
	Message      string
	Kouzou_kobun Kouzou1
}

func main() {
	// resultに構造体と値をセット
	result := Kouzou_oya{
		Status:  "22222",
		Message: "構造体テスト",
		Kouzou_kobun: Kouzou1{
			Var1: "aaaa",
			Var2: 2,
		},
	}

	//fmt.Println(result)

	// json 変換
	json_result, err := json.Marshal(result)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(string(json_result))

}
$ go run main.go | jq .
{
  "Status": "22222",
  "Message": "構造体テスト",
  "Kouzou_kobun": {
    "Var1": "aaaa",
    "Var2": 2
  }
}

Go言語は他の言語と違って変数の扱いが非常に難しく思えます。
構造体へのデータの参照や代入。
定義などを事前にしっかりしておかないと行けないっぽいので、Pythonの感覚だと動かないですね…。

1
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
1
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?