Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert map of map of interface to string

Tags:

go

I am newer to go lang and I have a type of variable like below:

type ResultData map[string]map[string][]interface{}

When I receive data in this variable, how do I convert the whole data into single string in Go?

like image 980
surendra Avatar asked Oct 15 '25 03:10

surendra


1 Answers

You can use something like Sprintf:

func main() {
    d1 := map[string][]interface{}{
        "a": []interface{}{20, "hello"},
        "b": []interface{}{100}}
    d2 := map[string][]interface{}{
        "x": []interface{}{"str", 10, 20},
    }

    m := make(map[string]map[string][]interface{})
    m["d1"] = d1
    m["d2"] = d2

    s := fmt.Sprintf("%v", m)
    fmt.Println(s)
}

Or you could also do that with the json module to convert to a JSON string with json.Marshal. If the actual runtime type behind your interface{} is marshal-able to JSON, json.Marshal will figure it out on its own.

b, _ := json.Marshal(m)
fmt.Println(string(b))
like image 163
Eli Bendersky Avatar answered Oct 17 '25 18:10

Eli Bendersky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!