Skip to content

Instantly share code, notes, and snippets.

@miguelmota
Last active November 24, 2022 09:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save miguelmota/04252b346d281b93f047bf9a20f73f04 to your computer and use it in GitHub Desktop.
Save miguelmota/04252b346d281b93f047bf9a20f73f04 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