2825 explained code solutions for 75 technologies


golangHow to convert struct to JSON


package main
import (
  "encoding/json"
  "fmt"
)
	
type person struct {
  Name string
  Age  int
}

func main() {
  sample := &person{Name: "Joe", Age: 90}
  res, _ := json.Marshal(sample)
}ctrl + c
package main

default package declaration

type person struct

declare sample struct

func main() {

declare main function that will be launched automatically

sample

sample variable of person struct

json.Marshal

converts given argument to JSON

res

variable will contain JSON string


Usage example

package main
import (
  "encoding/json"
  "fmt"
)

type person struct {
  Name string
  Age  int
}

func main() {
  sample := &person{Name: "Joe", Age: 90}
  res, _ := json.Marshal(sample)
  fmt.Println(string(res))
}
output
{"Name":"Joe","Age":90}