My use case is the Square API, where I want to retrieve a list of items, and iterate over some internal data, updating only the internal objects, not the main one.
The data is structured like this:
type ApiWrapper struct {
Cursor string `json:"cursor,omitempty"`
Objects []*Object `json:"objects,omitempty"`
}
type Object struct {
Type string `json:"type,omitempty"`
Id string `json:"id,omitempty"`
UpdatedAt time.Time `json:"updated_at,omitempty"`
CreatedAt time.Time `json:"created_at,omitempty"`
Version int64 `json:"version,omitempty"`
IsDeleted bool `json:"is_deleted,omitempty"`
ItemData *Item `json:"item_data,omitempty"`
ItemVariationData *ItemVariation `json:"item_variation_data,omitempty"`
}
type Item struct {
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
Visibility string `json:"visibility,omitempty"`
Variations []*Object `json:"variations,omitempty"`
}
type ItemVariation struct {
ItemId string `json:"item_id,omitempty"`
SKU string `json:"sku,omitempty"`
}
In this case, I want to fetch a list of ITEMs from the API, each of which will be of Type
ITEM
, and have ItemData
set. In the ItemData
, it will have a list of variations, each of which is an Object
of type ITEM_VARIATION
, with ItemVariationData
set.
What I want to do here is modify each of the ItemVariationData
items, and then render the Object
holding that variation's data.
I've tried implementing HandleJSONData()
such as:
func (e *Item) HandleJSONData(data map[string]interface{}) {
e.InternalData = data
}
and then using something like this to render the Object out:
func spewJSON(m map[string]any, obj any) {
structOut, err := json.Marshal(obj)
if err != nil {
panic(err)
}
err = json.Unmarshal(structOut, &m)
if err != nil {
panic(err)
}
out, err := json.MarshalIndent(m, "", "\t")
if err != nil {
panic(err)
}
fmt.Println(string(out))
}
func main() {
for _, itemObject := range result.Objects {
for _, variationObject := range itemObject.ItemData.Variations {
if variationObject.ItemVariationData.SKU == "" {
sku := makeSku()
log.Printf("item %s, variation %s, sku was empty, is now %s", variationObject.ItemVariationData.ItemId, variationObject.Id, sku)
variationObject.ItemVariationData.SKU = sku
} else {
log.Printf("item %s, variation %s, sku set to %s", variationObject.ItemVariationData.ItemId, variationObject.Id, variationObject.ItemVariationData.SKU)
}
spewJSON(variationObject.InternalData, variationObject)
}
}
}
However, while all the "unknown" fields in the Object render, the sub-object does not.
Any hints on where to go from here?