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

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"
	]
}

  

 

posted @ 2019-01-14 11:17  努力哥  阅读(1257)  评论(0编辑  收藏  举报