Json
https://mholt.github.io/json-to-go/
https://www.alexedwards.net/blog/how-to-properly-parse-a-json-request-body
https://stackoverflow.com/questions/17156371/how-to-get-json-response-from-http-get
JSON | GO |
---|---|
false, null, true | |
Objects {key1:value1, key2:value2, …} | map[string]interface{} |
Arrays [value1, value2, ... |
[]interface{} |
Numbers | |
Strings |
Go does not appear to allow alternative types, and func Unmarshal(data []byte, v interface{}) error puts everything in a catchall type empty interface interface{}.
These require type assertion to make them usable.
https://www.digitalocean.com/community/tutorials/how-to-use-interfaces-in-go
https://stackoverflow.com/questions/14025833/range-over-interface-which-stores-a-slice
package main
import (
"fmt"
"log"
"os"
"encoding/json"
"reflect"
)
func main() {
jsonBlob, err := os.ReadFile("/home/roblaing/webapps/hugo/content/joeblog/events.json")
/* jsonBlob, err := os.ReadFile("array.json") */
if err != nil {
log.Fatal(err)
} else {
var jobj map[string]interface{}
jerr := json.Unmarshal(jsonBlob, &jobj)
if jerr != nil {
fmt.Println("error:", jerr)
}
/* only works for jobj type map[string]interface{}, could be []interface{} */
for k := range jobj {
switch jobj[k].(type) {
case string:
fmt.Printf("%v %v\n", k, jobj[k])
case []interface{}:
s := reflect.ValueOf(jobj[k])
for i := 0; i < s.Len(); i++ {
fmt.Printf("%T\n", s.Index(i).Interface())
}
default:
fmt.Printf("%v %T\n", k, jobj[k])
}
}
}
}
The empty interfaceinterface{} is used to translate
the {key: val, …}
in the json file to a variable (keyvals above) holding a map[…]
.