Skip to content

Instantly share code, notes, and snippets.

@libchaos
Created September 15, 2021 06:39
Show Gist options
  • Save libchaos/bd2a04f7775b6ae639e0dcecd4818752 to your computer and use it in GitHub Desktop.
Save libchaos/bd2a04f7775b6ae639e0dcecd4818752 to your computer and use it in GitHub Desktop.
JSON_to_struct
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
)
type UserList struct {
Users []User `json:"users"`
}
type User struct {
Name string `json:"name"`
Type string `json:"type"`
Age int `json:"age"`
Social Social `json:"social"`
}
type Social struct {
Facebook string `json:"facebook"`
Twitter string `json:"twitter"`
}
var str string = `{
"users": [
{
"name": "Elliot",
"type": "Reader",
"age": 23,
"social": {
"facebook": "https://facebook.com",
"twitter": "https://twitter.com"
}
},
{
"name": "Fraser",
"type": "Author",
"age": 17,
"social": {
"facebook": "https://facebook.com",
"twitter": "https://twitter.com"
}
}
]
}
`
func writeToFile(filepath string, data string) error {
f, err := os.Create(filepath)
if err != nil {
return err
}
defer f.Close()
_, err = f.WriteString(str)
if err != nil {
return err
}
return nil
}
func readFromFile(filepath string) (string, error) {
bdata, err := ioutil.ReadFile(filepath)
if err != nil {
return "", err
}
sdata := string(bdata[:])
return sdata, nil
}
func main() {
err := writeToFile("users.json", str)
if err != nil {
panic(err)
}
data, err := readFromFile("users.json")
if err != nil {
panic(err)
}
fmt.Println("Successfully opened users.json")
var userList UserList
err = json.Unmarshal([]byte(data), &userList)
if err != nil {
panic(err)
}
for _, user := range userList.Users {
fmt.Println("User Type: ", user.Type)
fmt.Println("User Age: ", user.Age)
fmt.Println("User Name: ", user.Name)
fmt.Println("Facebook Url: ", user.Social.Facebook)
}
fmt.Println(userList)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment