golang-json construction and parsing: Marshal and Unmarsha, json to map

Go's json parsing: Marshal and Unmarshal

Go's json parsing: Marshal and Unmarshal
original link: https://blog.csdn.net/zxy_666/article/details/80173288

Json (Javascript Object Nanotation) is a data exchange format that is often used for front-end and back-end data transmission. Either end converts the data into a json string, and the other end parses the string into a corresponding data structure, such as string type, strcut object, etc.

The go language itself provides us with the json toolkit "encoding/json".

Json Unmarshal: Decodes a json string to the corresponding data structure.

json.Unmarshal parsing matching rule order

When parsing a json string, a "receiver" is required to receive the parsed data, and the receiver must pass a pointer when Unmarshal. Otherwise, the parsing will not report an error, but the data cannot be assigned to the receiver.

When parsing, the receiver can be defined by itself. The key in the json string automatically finds the matching item in the receiver and assigns it. The matching rules are:

  1. First find the json tag that is the same as the key, and assign it to the variable (such as Name) corresponding to the tag.
  2. If there is no json tag, look for the variable whose variable name is the same as the key from top to bottom. The variable name ignores the case of the variable that is the same as the key.
    The first match is assigned, and the subsequent matches are ignored.
    (The premise is that the variable must be exportable, that is, the first letter is capitalized).
  3. When there is an item in the receiver body that cannot be matched in the json string, the parsing will automatically ignore the item, and the item still retains the original value.

code demo

demo: basic use

Import: "github.com/vmihailenco/msgpack"
Call msgpack.Marshal for serialization
Call msgpack.Unmarshal for deserialization

type Person struct{
    
    
    Name string
    Age int
    Sex string
}
func writeJson(filename string)(err error){
    
    
    var persons []*Person
    for i := 0 ; i < 10; i++ {
    
    
        p := &Person{
    
    
                Name:fmt.Sprintf("name%d",i).
                Age:rand.Intn(100),
                Sex:"Man",
            }
        person = append(person,p)
    }
    data,err := msgpack.Marshal(persons)
    if err != nil {
    
    
        fmt.Printf("=marshal failed err:%v \n",err)
        return
    }
    err = ioutil.WriteFile(filename,data,0755)
    if err != nil{
    
    
        fmt.Printf("Write file failed,err:%v \n",err)
        return
    }
}
 
func readJson(filename string)(err error){
    
    
    var person []*Person
    data,err := ioutil.ReadFile(filename)
    if err!=nil {
    
    
        return
    }
    err = msgpack.Unmarshal(data,&persons)        
}

Encode data into json string

Go's json parsing: Marshal and Unmarshal
reference URL: https://www.jianshu.com/p/3534532e06ed

type Stu struct {
    
    
    Name  string `json:"name"`
    Age   int
    HIgh  bool
    sex   string
    Class *Class `json:"class"`
}

type Class struct {
    
    
    Name  string
    Grade int
}

func main() {
    
    
    //实例化一个数据结构,用于生成json字符串
    stu := Stu{
    
    
        Name: "张三",
        Age:  18,
        HIgh: true,
        sex:  "男",
    }

    //指针变量
    cla := new(Class)
    cla.Name = "1班"
    cla.Grade = 3
    stu.Class=cla

    //Marshal失败时err!=nil
    jsonStu, err := json.Marshal(stu)
    if err != nil {
    
    
        fmt.Println("生成json字符串错误")
    }

    //jsonStu是[]byte类型,转化成string类型便于查看
    fmt.Println(string(jsonStu))
}

result:

{
    
    "name":"张三","Age":18,"HIgh":true,"class":{
    
    "Name":"1班","Grade":3}}

As long as it is an exportable member (the first letter of the variable is capitalized), it can be converted to json. Because the member variable sex is not exportable, it cannot be converted to json.

If the variable is marked with a json tag, such as json:"name" next to Name, the converted json key will use the tag "name", otherwise the variable name will be used as the key, such as "Age", "HIgh".

The bool type is also a value value that can be directly converted to json. Channel, complex and functions cannot be encoded as json strings. Of course, the looping data structure is also not good, it will cause marshal to fall into an infinite loop.

A pointer variable, which is automatically converted to the value it points to during encoding, such as a cla variable.
(Of course, without passing a pointer, if the member Class of Stu struct is replaced with a Class struct type, the effect is exactly the same. Only the pointer is faster and can save memory space.)

Finally, it is emphasized that after json is encoded into a string, it is a pure string.

demo2:
insert image description here
Summary: json.Marshal(ki) returns the byte array corresponding to the json string.

json parsing

json.Unmarshal does not distinguish the case of the json field, as long as the letters are the same, it is not case-sensitive

convert json to map

package main
import (
    "encoding/json"
    "fmt"
)
//把请求包定义成一个结构体
type Requestbody struct {
    
    
    req string
}
//以指针的方式传入,但在使用时却可以不用关心
// result 是函数内的临时变量,作为返回值可以直接返回调用层
func (r *Requestbody) Json2map() (s map[string]interface{
    
    }, err error) {
    
    
    var result map[string]interface{
    
    }
    if err := json.Unmarshal([]byte(r.req), &result); err != nil {
    
    
        return nil, err
    }
    return result, nil
}
func main() {
    
    
    //json转map
    var r Requestbody
    r.req = `{"name": "xym","sex": "male"}`
    if req2map, err := r.Json2map(); err == nil {
    
    
        fmt.Println(req2map["name"])
        fmt.Println(req2map)
    } else {
    
    
        fmt.Println(err)
    }
}

Encoding tool json-to-go: json to go struct tool

json-to-go:https://mholt.github.io/json-to-go/

The tool instantly converts JSON to GO type definitions. Paste the JSON structure on the left and generate the equivalent GO type on the right!

Guess you like

Origin blog.csdn.net/inthat/article/details/106466166