Last active
January 3, 2018 03:53
-
-
Save eyeezzi/63bcfd91f67797b4e433d1cc9f282330 to your computer and use it in GitHub Desktop.
How to read JSON data that matches a struct in Go.
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" | |
) | |
type User struct { | |
Fname string | |
Lname string | |
Age int | |
} | |
func main() { | |
// Go stores JSON data as an array of bytes. | |
jstr := `{"fname":"john","lname":"doe","age":25}` | |
b := []byte(jstr) | |
// If the incoming JSON data *matches* our struct, Go can directly | |
// decode the JSON to our struct. | |
// See https://blog.golang.org/json-and-go for the matching rules. | |
var u User | |
// Unmarshalling => decoding JSON to Go object. | |
if err := json.Unmarshal(b, &u); err != nil { | |
fmt.Println(err.Error()) | |
} | |
fmt.Println(u.Fname) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment