Skip to content

Instantly share code, notes, and snippets.

@kangkyu
Last active June 19, 2019 01:53
Show Gist options
  • Save kangkyu/0a5d9b58f053d1632e081d1348603eef to your computer and use it in GitHub Desktop.
Save kangkyu/0a5d9b58f053d1632e081d1348603eef to your computer and use it in GitHub Desktop.
json.Marshal
package main
import (
"encoding/json"
"fmt"
)
type person struct {
First string
Last string
Age int
}
func main() {
p1 := person{
"James",
"Bond",
32}
p2 := person{
"Miss",
"Moneypenny",
27}
people := []person{p1, p2}
fmt.Printf("%T\n", people)
bs, err := json.Marshal(people)
if err != nil {
fmt.Println(err)
}
fmt.Printf("%T\n", string(bs))
fmt.Println(string(bs))
}
package main
import (
"encoding/json"
"fmt"
)
type person struct {
First string `json:"First"`
Last string `json:"Last"`
Age int `json:"Age"`
}
func main() {
s := `[{"First":"James","Last":"Bond","Age":32},{"First":"Miss","Last":"Moneypenny","Age":27}]`
bs := []byte(s)
fmt.Printf("%T\n", s)
fmt.Printf("%T\n", bs)
var people []person
err := json.Unmarshal(bs, &people)
// fmt.Printf("%T\n", err)
if err != nil {
fmt.Println(err)
}
fmt.Println("\nall the data", people)
for i, v := range people {
fmt.Println("\nNUMBER", i)
fmt.Println(v.First, v.Last, v.Age)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment