go语言之进阶篇通过map生成json

时间:2021-04-05 11:30:52

1、通过map生成json

示例1:

package main

import (
"encoding/json"
"fmt"
) func main() {
//创建一个map
m := make(map[string]interface{}, 4)
m["company"] = "itcast"
m["subjects"] = []string{"Go", "C++", "Python", "Test"}
m["isok"] = true
m["price"] = 666.666 //编码成json
result, err := json.Marshal(m)
if err != nil {
fmt.Println("err = ", err)
return
}
fmt.Println("result = ", string(result))
}

执行结果:

result =  {"company":"itcast","isok":true,"price":666.666,"subjects":["Go","C++","Python","Test"]}

示例2:

package main

import (
"encoding/json"
"fmt"
) func main() {
//创建一个map
m := make(map[string]interface{}, 4)
m["company"] = "itcast"
m["subjects"] = []string{"Go", "C++", "Python", "Test"}
m["isok"] = true
m["price"] = 666.666 //编码成json
result, err := json.MarshalIndent(m, "", " ")
if err != nil {
fmt.Println("err = ", err)
return
}
fmt.Println("result = ", string(result))
}

执行结果:

result =  {
"company": "itcast",
"isok": true,
"price": 666.666,
"subjects": [
"Go",
"C++",
"Python",
"Test"
]
}