I am new to GO and I am trying to consume json data from a variety of API's using GO and place them in struct's one of them Formats the data like so
{"MS": {
"last":"25",
"highestBid":"20"},
"GE": {
"last": "24",
"highestBid": "22"}
}
While I can find information on Consuming with dynamic keys, all the examples I found throw away the Outer most key as arbitrary and irrelevant. I need to use it as a key value pair like bellow:
{"MarketName": "GE", "last":"24","higestBid":"22"}
I understand Using Interface map but I cant figure out how to map the dynamic key to the struct as a key : value pair like above. My Code example to map leaving out the need key can be found at play ground Relevant Code
package main
import (
"encoding/json"
"fmt"
)
var jsonBytes = []byte(`
{"MS": {
"last":"25",
"highestBid":"20"},
"GE": {
"last": "24",
"highestBid": "22"}
}`)
type Market struct {
Last string
HighestBid string
}
func main() {
// Unmarshal using a generic interface
var f interface{}
err := json.Unmarshal(jsonBytes, &f)
if err != nil {
fmt.Println("Error parsing JSON: ", err)
}
fmt.Println(f)
}
as it stands it outputs
map[MS:map[last:25 highestBid:20] GE:map[highestBid:22 last:24]]
As I stated I am new to GO and as much help and explanation that i can get would be very appreciated
You're halfway there already, you just need to unmarshal into your struct and then massage the data a little:
type Market struct {
Name string
Last string
HighestBid string
}
func main() {
// Unmarshal using a generic interface
var f map[string]Market
err := json.Unmarshal(jsonBytes, &f)
if err != nil {
fmt.Println("Error parsing JSON: ", err)
return
}
markets := make([]Market, 0, len(f))
for k,v := range f {
v.Name = k
markets = append(markets,v)
}
fmt.Println(markets)
}
Working example here: https://play.golang.org/p/iagx8RWFfx_k
If a slice of Markets is a data structure that's going to be useful to you, you might wish to alias it and implement MarketList.UnmarshalJSON([]byte)
, like so:
type Market struct {
MarketName string
Last string
HighestBid string
}
type MarketList []Market
func (ml *MarketList) UnmarshalJSON(b []byte) error {
tmp := map[string]Market{}
err := json.Unmarshal(b, &tmp)
if err != nil {
return err
}
var l MarketList
for k, v := range tmp {
v.MarketName = k
l = append(l, v)
}
*ml = l
return nil
}
func main() {
ml := MarketList{}
// Unmarshal directly into a []Market alias
_ = json.Unmarshal(jsonBytes, &ml)
fmt.Printf("%+v
", ml)
}