This commit is contained in:
Sangeeth Sudheer 2024-05-01 22:46:04 +05:30
parent 2b310f1f7d
commit f042da5479
Signed by: x
GPG Key ID: F6D06ECE734C57D1
2 changed files with 59 additions and 2 deletions

55
json/json.go Normal file
View 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)
}

View File

@ -25,7 +25,8 @@ package main
// import "git.sangeeth.dev/gobyexample/stringfuncs" // import "git.sangeeth.dev/gobyexample/stringfuncs"
// import "git.sangeeth.dev/gobyexample/formatting" // import "git.sangeeth.dev/gobyexample/formatting"
// import "git.sangeeth.dev/gobyexample/templates" // 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() { func main() {
// runes.Runes() // runes.Runes()
@ -53,5 +54,6 @@ func main() {
// stringfuncs.StringFuncs() // stringfuncs.StringFuncs()
// formatting.Formatting() // formatting.Formatting()
// templates.Templates() // templates.Templates()
regex.Regex() // regex.Regex()
json.Json()
} }