Hey
I am very new with go i am developing a simple bot that works with httprequest
How i can parse a string like this
:string{“error”:[],“result”:{“KFEE”:{“aclass”:“currency”,“altname”:“FEE”,“decimals”:2,“display_decimals”:2},“XDAO”:
in something that i coudl manage better to work… for example struct or json…
If the string did not start with “:string”, it would be a valid JSON string, and you could decode it with the json.Unmarshal function.
From your other post (that you erroneously posted into the “Jobs” subforum, BTW), I conclude you want to access the Web API of kraken.com and parse the results. The API returns JSON data, so you can use standard JSON decoding to parse this data into a struct.
And this one is a really helpful tool: Paste some JSON and get the required Go structs back. https://mholt.github.io/json-to-go/
(From the creator of Caddyserver.)
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
)
type Result struct {
Unixtime int `json:"unixtime"`
Format string `json:"rfc1123"`
}
type Time struct {
Error []string `json:"error"`
Result `json:"result"`
}
func main() {
resp, err := http.Get("https://api.kraken.com/0/public/Time")
if err != nil {
log.Fatalln(err)
}
defer resp.Body.Close()
t := new(Time)
if err := json.NewDecoder(resp.Body).Decode(t); err != nil {
log.Fatalln(err)
}
if len(t.Error) > 0 {
log.Fatalln(t.Error)
}
fmt.Printf("Format: %s\nUnixtime: %d\n", t.Format, t.Unixtime)
}
Edit: You could also embed the Result struct directly inside of the Time struct like the following if you wanted to, instead of using composition: https://play.golang.org/p/AE_PpYWsYt.
In this case I would use the json.NewDecoder.Decode(t) since it will be reading directly from resp.Body.
In general if you are going to decode directly from an io.Reader, I would use json.NewDecoder.Decode but if you already have the bytes for what you want to use to decode, then use json.Unmarshal.