Created
October 16, 2017 21:11
-
-
Save henvic/2dadc148e603710c66c3f0bb3e5851f7 to your computer and use it in GitHub Desktop.
Simple dirty example of using Go's json.Marshal and json.Unmarshal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"log" | |
) | |
// Event to record | |
type Event struct { | |
ID string `json:"id"` | |
Priority int `json:"priority"` | |
Type string `json:"event_type,omitempty"` | |
Tags []string `json:"tags,omitempty"` | |
Extra map[string]string `json:"extra,omitempty"` | |
} | |
// User of the system | |
type User struct { | |
ID string `json:"id"` | |
Name string `json:"name"` | |
} | |
func marshalEvent(e Event) ([]byte, error) { | |
bin, err := json.MarshalIndent(&e, "", " ") | |
if err != nil { | |
return nil, err | |
} | |
return bin, nil | |
} | |
func marshalAndPrintEvent(e Event) error { | |
bin, err := marshalEvent(e) | |
if err != nil { | |
return err | |
} | |
fmt.Println("Event data from object:") | |
fmt.Println(string(bin)) | |
fmt.Println("") | |
return nil | |
} | |
func unmarshalUser(user []byte) (User, error) { | |
var u User | |
err := json.Unmarshal(user, &u) | |
return u, err | |
} | |
func unmarshalUserAndPrintName(userJSON string) error { | |
var user, err = unmarshalUser([]byte(userJSON)) | |
if err != nil { | |
return err | |
} | |
fmt.Printf("User name: %s\n", user.Name) | |
return nil | |
} | |
var example = Event{ | |
ID: "shutdown", | |
Priority: 4, | |
Tags: []string{ | |
"forced", | |
"remote", | |
}, | |
Extra: map[string]string{ | |
"user": "henrique", | |
}, | |
} | |
var userJSON = `{ | |
"id": "abcd", | |
"name": "Bruna" | |
}` | |
func main() { | |
if err := marshalAndPrintEvent(example); err != nil { | |
log.Fatal(err) | |
} | |
if err := unmarshalUserAndPrintName(userJSON); err != nil { | |
log.Fatal(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment