The array elements are objects with a single field: either "open" or "close".
How to handle this in Go?
You want to parse this JSON into Go structs.
The main challenge is that each element can have either the "open" key or the "close" key, but not both, and the key name determines the meaning.
There are a few ways to handle this.
Suggested approach: Use a struct with pointers and custom unmarshalling
You can create a Go struct like:
go
type TimeEntry struct {
Open *int `json:"open,omitempty"`
Close *int `json:"close,omitempty"`
}
Because only one of Open or Close will be set.
For example:
go
package main
import (
"encoding/json"
"fmt"
)
type TimeEntry struct {
Open *int `json:"open,omitempty"`
Close *int `json:"close,omitempty"`
}
func main() {
data := []byte(`[
{"open": 28800},
{"close": 72000}
]`)
var entries []TimeEntry
err := json.Unmarshal(data, &entries)
if err != nil {
panic(err)
}
for _, e := range entries {
if e.Open != nil {
fmt.Printf("Open: %d\n", *e.Open)
}
if e.Close != nil {
fmt.Printf("Close: %d\n", *e.Close)
}
}
}
Output:
code
Open: 28800
Close: 72000
This works fine for simple cases.
If you want a cleaner abstraction
If you want to abstract better and parse each entry as a single time with a type, you can add custom unmarshaling:
go
type TimeEntry struct {
Type string // "open" or "close"
Value int
}
func (t *TimeEntry) UnmarshalJSON(data []byte) error {
// data is something like: {"open":28800} or {"close":72000}
var obj map[string]int
if err := json.Unmarshal(data, &obj); err != nil {
return err
}
if open, ok := obj["open"]; ok {
t.Type = "open"
t.Value = open
} else if close, ok := obj["close"]; ok {
t.Type = "close"
t.Value = close
} else {
return fmt.Errorf("invalid entry: %s", string(data))
}
return nil
}
Usage:
go
func main() {
data := []byte(`[
{"open": 28800},
{"close": 72000}
]`)
var entries []TimeEntry
if err := json.Unmarshal(data, &entries); err != nil {
panic(err)
}
for _, e := range entries {
fmt.Printf("%s: %d\n", e.Type, e.Value)
}
}
This produces:
code
open: 28800
close: 72000
Summary
You can easily decode into a struct with two *int pointers for open and close.
Optionally implement UnmarshalJSON for cleaner API and stronger guarantees.
Since the key changes, you usually decode into a map and determine which key exists.
In your top-level struct, monday can be map[string][]TimeEntry or a dedicated struct.
If you want, I can help you write a complete Go struct representing the whole API response with days as keys. Just ask!