go 解析生成json、yaml

go 解析生成json、yaml,第1张

go 解析生成json、yaml 解析json数据获取json数据解析json数据 有必要建结构体解析json数组 解析json数据 没有必要建结构体返回值判断 发送json数据生成json数据发送 json数据 yaml <->jsonstruct生成yamlyaml 转 json

json学习笔记:JSON的数据类型

解析json数据 获取json数据

1.你要访问的url
2.读取resp的body

req, err := http.NewRequest("GET", dest_version_url,nil)
cookie := &http.Cookie{Name:"token",Value:"ehqhiqhiuhw82231bjbasaass"}
req.AddCookie(cookie)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil{
	panic(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
	fmt.Println("ERROR!: ", err)
}
jsondata := string(body)
解析json数据 有必要建结构体

你事先知道要传送json的格式,你想从json数据中提取你想要的东西

1 . 定义 json数组对应的结构体,整体对应slice
2.使用 Json Unmarshal将json字符串解码到相应的数据结构
3.你不想获取某些字段,可以把某些字段开头小写,或者直接去掉。

type Server_info struct {
	Server_name string
	Server_IP string
	Server map[string]string
	Client map[string]string
}

type Server_Info_Slice struct {
	RectCode int
	Server_info []Server_info
}

func main() {
	var serverList_Str = `{"retcode":0,"server_info":[{"server_name":"112","server_ip":"LALLAL","server":{"cpu":"1","disk":"3","memory":"2"},"client":{"cpu":"4","disk":"6","memory":"5"}}]}`
	var serverInfoSlice Server_Info_Slice
	json.Unmarshal([]byte(serverList_Str),&serverInfoSlice)
	//fmt.Println(serverInfoSlice)
	for _,serverInfoi := range serverInfoSlice.Server_info {
		fmt.Println("server_name-->",serverInfoi.Server_name)
	}
}
解析json数组

结构体只需要把json对应的字段开头大写,其余下划线,小写都不要变。

type Spec struct{
	Package_url string `yaml:"package_url"`
}
type Applicationconfig struct {
    Appcation string  `yaml:"appcation"`
    Version   float64 `yaml:"version"`
    Spec      Spec
}
type Application_Config_Slice struct {
    Applicationconfig []Applicationconfig
}

var appconfigstr=`[{
    "appcation": "nginx",
    "version": 6.2,
    "spec": {
      "package_url": "http://xxxxx.com"
     }
  }]`


func main() {
    var appconfigjsonHead =`{"applicationconfig":`
    appConfigJson :=fmt.Sprintf("%s%s}", appconfigjsonHead,appconfigstr)
    var applicationConfigSlice Application_Config_Slice
    json.Unmarshal([]byte(appConfigJson),&applicationConfigSlice)
    fmt.Println(applicationConfigSlice.Applicationconfig[0])
}
解析json数据 没有必要建结构体

判断htttp 返回值啊啥的,无需遍历数组的情况下用。

导入包:“github.com/bitly/go-simplejson”

func main() {
	buf := bytes.NewBuffer([]byte(`{
        "test": {
			"retcode": 0,
            "array": [1, "2", 3],
            "arraywithsubs": [
                {"subkeyone": 1},
                {"subkeytwo": 2, "subkeythree": 3}
            ],
            "bignum": 8000000000
        }
    }`))
	js, err := simplejson.NewFromReader(buf)
	if err != nil || js == nil{
		log.Fatal("something wrong when call NewFromReader")
	}

	fmt.Println(js) //&{map[test:map[array:[1 2 3] arraywithsubs:[map[subkeyone:1] map[subkeythree:3 subkeytwo:2]] bignum:8000000000 retcode:0]]}&{map[test:map[array:[1 2 3] arraywithsubs:[map[subkeyone:1] map[subkeythree:3 subkeytwo:2]] bignum:8000000000 retcode:0]]}
	arr, err := js.Get("test").Get("array").Array()
	if err != nil || arr == nil{
		log.Fatal("something wrong when call Get and Array")
	}
	fmt.Println(arr) //[1 2 3]
	
	fmt.Println(js.Get("test").Get("retcode").MustInt64()) //0
	fmt.Println(js.Get("test").Get("array").MustArray()) //[1 2 3]
	fmt.Println(js.Get("test").Get("arraywithsubs").GetIndex(0).MustMap()) //map[subkeyone:1]
	fmt.Println(js.Get("test").Get("bignum").MustInt64()) //8000000000
}
返回值判断
returnBody := `{"retcode": -1, "errmsg": "non backup owner"}`
js, err := simplejson.NewFromReader(bytes.NewBuffer([]byte(returnBody)))
if err != nil || js == nil {
	log.Fatal("something wrong when call NewFromReader")
}
returnCode := js.Get("retcode").MustInt64()
if returnCode != 0 {
	log.Fatal("ERROR--> " + js.Get("errmsg").MustString())
}
发送json数据

你事先知道要传送json的格式 , 你想把变量放进json

生成json数据

1.定义 json数组对应的结构体,整体对应slice
2.使用 Json Marshal 将数据编码成json字符串

type Server_info struct {
	Server_name string `json:"server_name"`
	Server_IP string `json:"server_ip"`
	Server map[string]string  `json:"server"`
	Client map[string]string `json:"client"`
}

type Server_Info_Slice struct {
	RectCode int `json:"retcode"`
	Server_info []Server_info  `json:"server_info"`
}

func main() {
	var serverList Server_Info_Slice
	serveri := Server_info{
		Server_name:"112",
		Server_IP:"LALLAL",
		Server: map[string]string{
			"cpu": "1",
			"memory": "2",
			"disk": "3",
		},
		Client: map[string]string{
			"cpu": "4",
			"memory": "5",
			"disk": "6",
		},
	}
	serverList.RectCode = 0
	serverList.Server_info= append(serverList.Server_info, serveri)
	json_server, err := json.Marshal(serverList)
	if err != nil {
		fmt.Println("json err:", err)
	}
	fmt.Println(string(json_server))
}

生成空json

type mdata struct {
   data string  `json:"data"`
}

func main(){
   data1 := &mdata{"lal"}
   json_mydata, _ := json.Marshal(data1)
   fmt.Println(string(json_mydata))
}
发送 json数据

1.准备好json
2.准备你的url

json_data, _ := json.Marshal(data)
var json_data_byte = []byte(json_data)
fmt.Println("json-->",bytes.NewBuffer(json_data_byte))
req, err := http.NewRequest("POST", dest_url, bytes.NewBuffer(json_data_byte))
req.Header.Set("Content-Type", "application/json")
cookie := &http.Cookie{Name:"token",Value:"najnkjsiauhdi9w3832233"}
req.AddCookie(cookie)
client := &http.Client{}
client.Do(req)

配置文件生成
参考文章:使用golang解析yaml、json、xml文件

yaml <->json

struct生成json
struct生成yaml
yaml转json

struct生成yaml
package main
import (
	"github.com/spf13/viper"
	"os"
)
type Aa struct {
	A1 int
	A2 string
}

/*
GenerateYaml:生成yaml文件
Yamlfile:文件路径
key:yaml 的key
value: yaml 的value
*/
func GenerateYaml(yamlfile, key string,value interface{}) error {
	filename := string(yamlfile)
	var viperobj = viper.New()
	viperobj.SetConfigFile(filename)
	viperobj.SetConfigType("yaml")
	if err := viperobj.ReadInConfig(); err != nil {
		os.Create(filename)
	}
	viperobj.Set(key,value)
	return viperobj.WriteConfig()
}

func main() {
	test := Aa{
		A1: 1,
		A2: "2222",
	}
	Set("aa.yaml","bb",test)
}

yaml 转 json
import (
    "encoding/json"
    "fmt"
    "gopkg.in/yaml.v2"
    "io/ioutil"
)

type KafkaCluster struct {
    Spec       Spec     `yaml: "spec"`
}

type Spec struct {
    Name     string `yaml: "name"`
    Conditions []Conditions `yaml: "conditions"`
}

type Conditions struct {
    ContainerPort string   `yaml:"containerPort"`
    Requests      map[string]string `yaml: "requests"`
}

func main() {
    var c KafkaCluster
    //读取yaml配置文件, 将yaml配置文件,转换struct类型
    conf := c.getConf()
    //将对象,转换成json格式
    data, err := json.Marshal(conf)
    if err != nil {
        fmt.Println("err:\t", err.Error())
        return
    }
    //最终以json格式,输出
    fmt.Println("data:\t", string(data))
}

//读取Yaml配置文件,
//并转换成conf对象  struct结构
func (kafkaCluster *KafkaCluster) getConf() *KafkaCluster {
    //应该是 绝对地址
    yamlFile, err := ioutil.ReadFile("D:/zhuzhu11/Desktop/yw/aa.txt")
    if err != nil {
        fmt.Println(err.Error())
    }
    //err = yaml.Unmarshal(yamlFile, kafkaCluster)
    err = yaml.UnmarshalStrict(yamlFile, kafkaCluster)
    if err != nil {
        fmt.Println(err.Error())
    }
    return kafkaCluster  
}

报错:Yaml文件格式错误mapping values are not allowed in this context
辅助工具:https://www.bejson.com/validators/yaml_editor/
参考文章:Yaml文件格式错误

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/995806.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存