본문 바로가기

Programming Language/golang

golang struct type을 JSON으로 Print 하기

package main

import (
	"encoding/json"
	"fmt"
)

type Person struct {
	Name string
	Age  int
}

func main() {
	myStruct := Person{"dvwy", 145}
	fmt.Println("=======")
	fmt.Println(myStruct)
	fmt.Println(prettyPrint(myStruct))
}

func prettyPrint(i interface{}) string {
	s, _ := json.MarshalIndent(i, "", "\t")
	return string(s)
}

결과는 다음과 같습니다.

{dvwy 145}
{
        "Name": "dvwy",
        "Age": 145
}

 

출처 : https://stackoverflow.com/a/51270134

 

How to print struct variables in console?

How can I print (to the console) the Id, Title, Name, etc. of this struct in Golang? type Project struct { Id int64 `json:"project_id"` Title string `json:"title&qu...

stackoverflow.com

 

반응형