Home > database >  Assign dynamic key to a predefined struct Golang
Assign dynamic key to a predefined struct Golang

Time:09-13

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

CodePudding user response:

You can use map, map[key]type structure

CodePudding user response:

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.

  •  Tags:  
  • go
  • Related