Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

map[string]interface{} to struct with json tags

Tags:

go

I need to convert a map[string]interface{} whose keys are json tag names to struct

type MyStruct struct {
    Id           string `json:"id"`
    Name         string `json:"name"`
    UserId       string `json:"user_id"`
    CreatedAt    int64  `json:"created_at"`
}

The map[string]interface{} has keys id, name, user_id, created_at. I need to convert this into struct.

like image 322
AbA Avatar asked Feb 26 '18 17:02

AbA


People also ask

How do you map a struct to an interface?

There are two steps: Convert interface to JSON Byte. Convert JSON Byte to struct.

What is MAP string interface Golang?

The difference between those two types is just what it seems: interface{} is the "any" type, since all types implement the interface with no functions. map[string]interface{} is a map whose keys are strings and values are any type.


2 Answers

If I understood well, you have a map and want to fill struct by. If it's first change it to jsonString and then Unmarshal it to struct

package main

import (
    "encoding/json"
    "fmt"
)

type MyStruct struct {
    Id           string `json:"id"`
    Name         string `json:"name"`
    UserId       string `json:"user_id"`
    CreatedAt    int64  `json:"created_at"`
}

func main() {
    m := make(map[string]interface{})
    m["id"] = "2"
    m["name"] = "jack"
    m["user_id"] = "123"
    m["created_at"] = 5
    fmt.Println(m)

    // convert map to json
    jsonString, _ := json.Marshal(m)
    fmt.Println(string(jsonString))

    // convert json to struct
    s := MyStruct{}
    json.Unmarshal(jsonString, &s)
    fmt.Println(s)

}

Update 2021-08-23

while I see ,this post is useful. I posted a complete sample on my gist, please check it here

like image 187
irmorteza Avatar answered Oct 19 '22 04:10

irmorteza


You can use https://github.com/mitchellh/mapstructure for this. By default, it looks for the tag mapstructure; so, it's important to specify TagName as json if you want to use json tags.

package main

import (
    "fmt"
    "github.com/mitchellh/mapstructure"
)

type MyStruct struct {
    Id        string `json:"id"`
    Name      string `json:"name"`
    UserId    string `json:"user_id"`
    CreatedAt int64  `json:"created_at"`
}

func main() {
    input := map[string]interface{} {
        "id": "1",
        "name": "Hello",
        "user_id": "123",
        "created_at": 123,
    }
    var output MyStruct
    cfg := &mapstructure.DecoderConfig{
        Metadata: nil,
        Result:   &output,
        TagName:  "json",
    }
    decoder, _ := mapstructure.NewDecoder(cfg)
    decoder.Decode(input)

    fmt.Printf("%#v\n", output)
    // main.MyStruct{Id:"1", Name:"Hello", UserId:"123", CreatedAt:123}
}
like image 20
Bless Avatar answered Oct 19 '22 05:10

Bless