AbA
AbA

Reputation: 311

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

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.

Upvotes: 31

Views: 61358

Answers (3)

irmorteza
irmorteza

Reputation: 1654

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

Upvotes: 42

Jakub
Jakub

Reputation: 295

If you consider the speed then Mapstructure is 40 percent slower then jsoniter.ConfigFastest where you test on similar struct

type Message struct {
    ID        string      `json:"id,omitempty"`
    Type      string      `json:"type"`
    Timestamp uint64      `json:"timestamp,omitempty"`
    Data      interface{} `json:"data"`
}

And you want to check message type by Type == "myType" and then marshal/unmarshal only Data field (which will be map[string]interface{} after first unmarshal) Quite similar scenario as you mentioned and the reason why the https://github.com/mitchellh/mapstructure is used for...

goos: windows
goarch: amd64
cpu: AMD Ryzen Threadripper 3960X 24-Core Processor 
BenchmarkMarshalUnmarshal
BenchmarkMarshalUnmarshal-48                      521784          2049 ns/op         871 B/op         20 allocs/op
BenchmarkMarshalUnmarshalConfigFastest
BenchmarkMarshalUnmarshalConfigFastest-48         750022          1591 ns/op         705 B/op         15 allocs/op
BenchmarkMapstructure
BenchmarkMapstructure-48                          480001          2546 ns/op        1225 B/op         25 allocs/op
BenchmarkDirectStruct
BenchmarkDirectStruct-48                         3096033           391.7 ns/op        88 B/op          3 allocs/op
PASS

Upvotes: 1

Bless
Bless

Reputation: 5370

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}
}

Upvotes: 23

Related Questions