Add json
This commit is contained in:
parent
2b310f1f7d
commit
f042da5479
55
json/json.go
Normal file
55
json/json.go
Normal file
@ -0,0 +1,55 @@
|
||||
package json
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
||||
var f = fmt.Println
|
||||
|
||||
type person1 struct {
|
||||
Name string
|
||||
Age uint
|
||||
}
|
||||
|
||||
type person2 struct {
|
||||
Name string `json:"name"`
|
||||
Age uint `json:"age"`
|
||||
}
|
||||
|
||||
type person3 struct {
|
||||
Name string `json:"name"`
|
||||
Age uint `json:"age"`
|
||||
Albums []string `json:"albums"`
|
||||
}
|
||||
|
||||
func Json() {
|
||||
stringBytes, _ := json.Marshal("foo")
|
||||
f("string =>", string(stringBytes))
|
||||
|
||||
p1Bytes, _ := json.Marshal(&person1{"Abel", 34})
|
||||
f("person1 =>", string(p1Bytes))
|
||||
|
||||
p2Bytes, _ := json.Marshal(&person2{"Abel", 34})
|
||||
f("person2 =>", string(p2Bytes))
|
||||
|
||||
jsonBytes := []byte(`{"name": "Abel", "age": 34, "albums": ["Dawn FM"]}`)
|
||||
pMap := map[string]any{}
|
||||
json.Unmarshal(jsonBytes, &pMap)
|
||||
|
||||
uname := pMap["name"].(string)
|
||||
f("map[name] =>", uname)
|
||||
ualbums := pMap["albums"].([]any)
|
||||
album0 := ualbums[0].(string)
|
||||
f("map[albums][0] =>", album0)
|
||||
|
||||
p3 := &person3{}
|
||||
json.Unmarshal(jsonBytes, &p3)
|
||||
|
||||
f("p3 =>", p3)
|
||||
|
||||
f("Directly writing to stderr:")
|
||||
enc := json.NewEncoder(os.Stderr)
|
||||
enc.Encode(&p3)
|
||||
}
|
6
main.go
6
main.go
@ -25,7 +25,8 @@ package main
|
||||
// import "git.sangeeth.dev/gobyexample/stringfuncs"
|
||||
// import "git.sangeeth.dev/gobyexample/formatting"
|
||||
// import "git.sangeeth.dev/gobyexample/templates"
|
||||
import "git.sangeeth.dev/gobyexample/regex"
|
||||
// import "git.sangeeth.dev/gobyexample/regex"
|
||||
import "git.sangeeth.dev/gobyexample/json"
|
||||
|
||||
func main() {
|
||||
// runes.Runes()
|
||||
@ -53,5 +54,6 @@ func main() {
|
||||
// stringfuncs.StringFuncs()
|
||||
// formatting.Formatting()
|
||||
// templates.Templates()
|
||||
regex.Regex()
|
||||
// regex.Regex()
|
||||
json.Json()
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user