在单值上下文中使用多值的json.Marshal()函数。

huangapple go评论88阅读模式
英文:

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函数返回两个值([]byteerror)。你需要存储第一个返回值,然后进行转换:

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

huangapple
  • 本文由 发表于 2017年8月27日 09:13:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/45900911.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定