Assign dynamic key to a predefined struct Golang

Viewed 24

I have a struct defined in my project with key value pair as

type ObjectInterface struct {
    Vegetables int `json:"vegetable"`
    Fruits     int `json:"fruits"`
    Nuts       int `json:"nuts"`
}

Now i have got a payload to be assigned in this struct variable as per whatever key is i get from payload

fetchObject := ObjectInterface{
                 [dynamicKey]: 'value'
                }

How do i achieve this in golang

2 Answers

You can use map, map[key]type structure

You can achieve this by unmarshalling your payloads into map[string]interface{}{}. For Example:

var fetchObject map[string]interface{}{}

json.unmarshall(ObjectInterface, &fetchObject)

The objectInterface is the payload that you get.

Related