Skip to content

Instantly share code, notes, and snippets.

@YagmurOzden
Forked from miguelmota/json_marshal_unmarshal.go
Created November 24, 2022 09:00
Show Gist options
  • Save YagmurOzden/026e8fb1252c7e2d275862ca642647e8 to your computer and use it in GitHub Desktop.
Save YagmurOzden/026e8fb1252c7e2d275862ca642647e8 to your computer and use it in GitHub Desktop.
Golang JSON Marshal (struct to string) (M for "Make json") and Unmarshal (string to struct) (U for "Unmake json") example
package main
import (
"encoding/json"
"fmt"
)
func main() {
type MyStruct struct {
Message string `json:"message"`
}
mystruct := &MyStruct{
Message: "hello",
}
// convert struct to json string
jsonBytes, err := json.Marshal(mystruct)
fmt.Println(string(jsonBytes), err) // {"message":"hello"} <nil>
var mystruct_2 *MyStruct
// convert json string to struct
err = json.Unmarshal(jsonBytes, &mystruct_2)
fmt.Println(mystruct_2, err) // &{hello} <nil>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment