英文:
multiple-value json.Marshal() in single-value context
问题
你可以在这里看到这段代码:
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)))
}
它返回以下错误:
tmp/sandbox100532722/main.go:13:33: multiple-value json.Marshal() in single-value context.
我该如何修复这个错误?
英文:
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?
答案1
得分: 22
你正在尝试进行的字符串转换需要一个参数,但是json.Marshal
函数返回两个值([]byte
和error
)。你需要存储第一个返回值,然后进行转换:
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))
}
英文:
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))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论