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

      

  • 相关阅读:
    微信开发之注册公众号(二)
    我开通个人博客了~~~~
    微信开发之启用开发者模式(三)
    float浮动属性
    数组的定义与特点
    块级元素和行内元素
    对于if判断和switch选择的入门理解
    Form表单
    不知名的作业
    自我介绍
  • 原文地址:https://www.cnblogs.com/nulige/p/10265839.html
Copyright © 2020-2023  润新知