-
Hello! I am trying to figure out capabilities of this library - and whether it can parse into a Struct without knowing the shape. Also I am trying to find out how to print a proper indented version from an API Response. For example so far I have this - func MakeAPICallSonic(url string) error {
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
// Is this recommended way of initializing it? Trying to understand when to use AST versus Decoder
root, err := sonic.Get(body)
if err != nil {
return err
}
// PRINT RAW JSON using Sonic
rawJSON, _ := root.Raw()
fmt.Printf("JSON Response:\n%s\n", rawJSON)
// PRINT RAW JSON using Sonic - returns result as a string similar to encoding/json
jsonResp, _ := root.MarshalJSON()
fmt.Printf("JSON Response:\n%s\n", jsonResp)
return nil
} Couple Questions -
PrettyPrintJSON("https://api.sampleapis.com/beers/ale")
func PrettyPrintJSON(url string) error {
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
var result interface{}
err = json.Unmarshal(body, &result)
if err != nil {
return err
}
prettyJSON, err := json.MarshalIndent(result, "", " ")
if err != nil {
return err
}
fmt.Printf("Pretty Printed JSON\n\n%s", prettyJSON)
return nil
}
Sorry for several questions - understanding idiomatic ways to use the Library based on how it has been designed. Looking to incorporate usage incrementally into large hyper scale distributed real time systems - and want to understand API design to build on top of. `` Would really appreciate any help - amazing library and looking forward to using it more! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
For question 1: It's mainly about cocurrency safty --- you can pass any
|
Beta Was this translation helpful? Give feedback.
For question 1: It's mainly about cocurrency safty --- you can pass any
[]byte
to sonic as long as you can ensure it is not being used by other goroutines at the same time.For question 2: At present sonic doesn't implement json formalization by itself. You can use
encoding/json
's API to printFor question 3: not totally understand your question. I guess you mean you didn't know the whole schema for json but has some known fields --- for this situation you have two choice:
Unmarshal()
sonic.Get()
. Translate these known fields into pathes …