I've been bashing my head about this for a while now. I have a JSON file that must be in the following format that I need to iterate through and use IF statements on in Go:
[
[
{
"configName": "customer"
},
{
"config": [
{
"emailSubject": "New customer added"
},
{
"text": "Hi test 2"
},
{
"text": "added 2"
}
]
}
]
[
{
"configName": "customerAndUser"
},
{
"config": [
{
"emailSubject": "New customer added"
},
{
"text": "Hi, test 1"
},
{
"text": "added 1"
}
]
}
]
]
And I want to put it into a struct, like this:
type Config [][]struct {
configName string `json: configName`
config []struct {
Text string `json: text`
EmailSubject string `json: emailSubject`
} `json: config`
}
I can unmarshal the data fine, like this:
configData, err := ioutil.ReadFile("testing-config.json")
if err != nil {
fmt.Println(err)
}
var configDataUnmarshalled Config
json.Unmarshal([]byte(configData), &configDataUnmarshalled)
And then the data prints, sort of okay, but here is where things get a little strange: the print statement is returning blanks for the items that I do not specify to print. Here is a sample of what's printed when I print the unmarshalled data:
Print output from unmarshalled data:
[[{customer []} { [{ New customer added} {hi test 2 } {added 2 }]}] [{customerAndUser []} { [{ New customer added} {hi test 1 } {added 1 }]}]]
But then I can't seem to use IF statements or loop over the elements in the config key!
IF statement being ignored in the for loop (see output below code)
for _, configs := range configDataUnmarshalled {
for _, configurations := range configs {
fmt.Println("These are the top level elements in my struct: ", configurations.ConfigName)
if configurations.ConfigName == "customerAndUser" {
for _, config := range configurations.Config {
fmt.Println(config)
}
}
}
}
This is what is printed:
These are the top level elements in my struct: customer
These are the top level elements in my struct:
These are the top level elements in my struct: customerAndUser
These are the top level elements in my struct:
From the FOR loop you can see that I want to access the data when a config is of a certain name, in this case "customerAndUser"
Here the IF statement is being ignored completely
I have two things I want to understand/solve:
- How can I access the data following an IF statement
- Why is the program printing blanks?
Desired output would be printing out the emailSubject, and the two Text element's data to the console for the config with name customerAndUser
What should be printed:
New customer added
hi test 1
added 1
Thanks for your help