在Go中,你可以很容易地将一个地图转换成JSON字符串,使用 encoding/json包。如果地图包含字符串、数组、结构、数值或其他地图,这并不重要。你唯一要记住的是JSON只允许字符串键,所以如果你的地图中有一个整数键,它将被转换为字符串。
package main
import (
"encoding/json"
"fmt"
"log"
)
type color struct {
Name string `json:"name"`
HexCode string `json:"hex_code"`
}
func main() {
data := make(map[string]interface{})
data = map[string]interface{}{
"best_fruit": "apple", // string value
"best_vegetables": []string{"potato", "carrot", "cabbage"}, // array value
"best_websites": map[int]interface{}{ // map value
1: "gosamples.dev", // integer key, string value
},
"best_color": color{
Name: "red",
HexCode: "#FF0000",
}, // struct value
}
jsonBytes, err := json.MarshalIndent(data, "", " ")
if err != nil {
log.Fatal(err)
}
fmt.Println(string(jsonBytes))
}
json.MarshalIndent产生带缩进的JSON编码的地图。如果你需要没有缩进的输出,使用 json.Marshal.
输出。
{
"best_color": {
"name": "red",
"hex_code": "#FF0000"
},
"best_fruit": "apple",
"best_vegetables": [
"potato",
"carrot",
"cabbage"
],
"best_websites": {
"1": "gosamples.dev"
}
}