Usually we Unmarshal a json object in Go as:
I am kind of a noob in Go, so pardon me if some syntax seems incorrect below.
type Item struct {
Quantity int `json:"quantity,omitempty"`
Price float64 `json:"price,omitempty"`
Currency string `json:"currency,omitempty"`
}
output := &Item{}
err:= json.Unmarshal([]byte(data), output)
Now the catch is my json could be different at runtime depending on some field. Price could be string, array with different value or json containing currency and price in one object.
I have this mapping in the db, how could I write my code so that I would read that mapping of column name to type and then unmarshall it creating the suitable struct at runtime. For e.g. I need to unmarshall following JSON's in same code:-
{"Quantity": 5, "Price": 64.5, "Currency": "USD"}
{"Quantity": 5, "Purchase": {"Price": 64.5, "Currency": "USD"}}
I would already have mapping like Quantity -> int, Purchase -> JSON String
for second json with me in the DB.
tl;dr
Need to unmarshall json where structure changes at runtime on the basis of some parameters and I know the structure beforhand
Edit: Rephrase
I need function which will return me the object of above struct take json string and json format string as input.
CustomUnmarshal([]byte(data) []byte, format string) (*item){}
I have written a sample code here:-