Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple-value json.Marshal() in single-value context [duplicate]

Tags:

json

go

Here you can see this code:

package main

import (
    "fmt"
    "encoding/json"
)

func main() {
    map1 := map[string]map[string]interface{}{}
    map2 := map[string]interface{}{}
    map2["map2item"] = "map2item"
    map1["map2"] = map2
    fmt.Println(string(json.Marshal(map1)))
}

that returns this error:

tmp/sandbox100532722/main.go:13:33: multiple-value json.Marshal() in single-value context.

How do I fix this?

like image 433
sensorario Avatar asked Aug 27 '17 01:08

sensorario


1 Answers

The string conversion you are trying to perform requires a single argument, but the json.Marshal function returns two ([]byte and error). You need to store the first return value and then do the conversion:

package main

import (
    "fmt"
    "encoding/json"
)

func main() {
    map1 := map[string]map[string]interface{}{}
    map2 := map[string]interface{}{}
    map2["map2item"] = "map2item"
    map1["map2"] = map2
    b, err := json.Marshal(map1)
    if err != nil {
        panic(err)
    }
    fmt.Println(string(b))
}
like image 132
Tim Cooper Avatar answered Oct 29 '22 17:10

Tim Cooper