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

Posted 努力哥-运维自动化

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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"
	]
}

  

 

以上是关于go语音之进阶篇通过map生成json的主要内容,如果未能解决你的问题,请参考以下文章

go语音之进阶篇 channel介绍

go语音之进阶篇正则表达式

go语音之进阶篇接口的继承

go语音之进阶篇方法表达式

go语音之进阶篇Read的使用

go语音之进阶篇方法的重写