I want to unmarshal the following JSON data in Go:
b := []byte(`{"Asks": [[21, 1], [22, 1]] ,"Bids": [[20, 1], [19, 1]]}`)
I know how to do that, i define a struct like this:
type Message struct {
Asks [][]float64 `json:"Bids"`
Bids [][]float64 `json:"Asks"`
}
What i don't know is if there is a simple way to specialize this a bit more. I would like to have the data after the unmarshaling in a format like this:
type Message struct {
Asks []Order `json:"Bids"`
Bids []Order `json:"Asks"`
}
type Order struct {
Price float64
Volume float64
}
So that i can use it later after unmarshaling like this:
m := new(Message)
err := json.Unmarshal(b, &m)
fmt.Println(m.Asks[0].Price)
I don't really know how to easy or idiomatically do that in GO so I hope that there is a nice solution for that.
To parse JSON, we use the Unmarshal() function in package encoding/json to unpack or decode the data from JSON to a struct. Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v. Note: If v is nil or not a pointer, Unmarshal returns an InvalidUnmarshalError.
To unmarshal a JSON array into a slice, Unmarshal resets the slice length to zero and then appends each element to the slice. As a special case, to unmarshal an empty JSON array into a slice, Unmarshal replaces the slice with a new empty slice.
The json package includes Unmarshal() function which supports decoding data from a byte slice into values. The decoded values are generally assigned to struct fields, the field names must be exported and should be in capitalize format.
You can do this with by implementing the json.Unmarshaler
interface on your Order
struct. Something like this should do:
func (o *Order) UnmarshalJSON(data []byte) error {
var v [2]float64
if err := json.Unmarshal(data, &v); err != nil {
return err
}
o.Price = v[0]
o.Volume = v[1]
return nil
}
This basically says that the Order
type should be decoded from a 2 element array of floats rather than the default representation for a struct (an object).
You can play around with this example here: http://play.golang.org/p/B35Of8H1e6
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With