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" ] }
原文地址:https://www.cnblogs.com/nulige/p/10265839.html
时间: 2024-10-08 01:11:14