I’ve searched quite a bit for my specific use case but haven’t a solution, so I thought I’d ask. I’m learning Go at the moment, creating a module. But having trouble unmarshaling a json file into a struct. The contents of the json file are to be used as settings for the Asynq server since they might change and I don’t want to hardcode them.
The specific issue is that after reading the file and unmarshaling it, the content returns empty, or zero for int fields. Seems like I’m missing a step, perhaps, do a range through, but I can’t pinpoint it. Below is what I’m doing:
The struct:
type AsynqQueues struct {
Name string `json:"name"`
Priority int `json:"priority"`
Concurrency int `json:"concurrency"`
}
The contents of the json file, which I got from filePath:
{
“queues”: [
{
“name”: “critical”,
“priority”: 6
},
{
“name”: “default”,
“priority”: 3
},
{
“name”: “low”,
“priority”: 1
},
{
“concurrency”: 10
}
]
}
The function (I’m returning nil for now to be able to test that part of the code):
func MyAsynqServer(filePath string) *asynq.Server {
var settings AsynqQueues
file, err := os.ReadFile(filePath)
if err != nil {
fmt.Println("Error reading file:", err)
return nil
}
err = json.Unmarshal(file, &settings)
if err != nil {
fmt.Println("Error unmarshalling JSON:", err)
return nil
}
fmt.Printf("Name: %s, Priority: %d, Concurrency: %dn", settings.Name, settings.Priority, settings.Concurrency)
return nil
Since the json is an array of objects, I also tried creating another struct as below then calling the AsynqQueues struct from it. But in either case I get empty back:
type Queues struct {
AQueues AsynqQueues
}