遍历字段名称的结构后,通过括号表示法使用括号中的变量访问值

I have 2 JSON files one containing users, and another containing email templates

I'm looping through the code in the email templates, and when there is a key as a value, like this:

"keyToFind": "Username"

Then I want to get the value for Username in the other JSON file:

"Username": "ssmith"

KeyToFind can be a few different things, like Password or Group and I want to avoid writing a specific if statement

I'm trying to do this in my loop but it appears that I can't use a variable in bracket notation

for _, emailElements := range emailTemplates.EmailSpecification {
                for _, fieldName := range structs.Names(&User{}) {
                    if emailElements.KeyToFind == fieldName {
                        EmailBody.WriteString(user[fieldName])
                    }
                }

What the above is trying to do is loop through the elements in the email template, and then the fields in the Users struct; where an emailElement in the template JSON file of type KeyToFind is gotten, and this is the same as a field name in the struct; look up the user value for the KeyToFind

I could do this in Python without a problem

How can I rewrite line 4 to work in Go? --> user[FieldName]

The error I get is:

user[fieldName] (type User does not support indexing)

But if I write line 4 again to this:

user.Username

It will work fine, but that's obviously only for usernames, they could be Password or Group for the value in KeyToFind

Here are the JSON files:

Email template:

    "emailName": "customer",
    "emailSpecification": [
        {
            "emailSubject": "Hi"
        },
        {
            "text": "Username: "
        },
        {
            "keyToFind": "Username"
        }
]

I want to get the value of KeyToFind and search the properties in the User file and return the value from that property

User file:

[
{
    "UserType": "customer",
    "Username": "ssmith",
    "Password": "sophie"
}
]

I got it by converting the User struct to a map, once it's a map you can use the bracket notation with dot notation inside

In my context, I then had to convert to a string to pass into WriteString function that buffer needs

Here is the final version:

for _, emailElements := range emailTemplates.EmailSpecification {
                for _, fieldName := range structs.Names(&User{}) {
                    if emailElements.KeyToFind == fieldName {
                        EmailBody.WriteString(structs.Map(user)[emailElements.KeyToFind].(string))
                    }
                }
}

It's using the package:

"github.com/fatih/structs"