Home  >  Article  >  Backend Development  >  How to parse json format in golang

How to parse json format in golang

藏色散人
藏色散人forward
2021-01-25 14:42:532883browse

The following column golang tutorial will introduce to you how golang parses json format. I hope it will be helpful to friends in need!

The interactive data part between the client and the server in the project is json, so it has to be parsed on the server side. It is actually quite laborious to parse complex json.
The interactive data is similar to the following format:

{"sn":1,"ls":false,"bg":0,"ed":0,"ws":[{"bg":0,"cw":[{"sc":0,"w":"还"}]},{"bg":0,"cw":[{"sc":0,"w":"有点"}]},{"bg":0,"cw":[{"sc":0,"w":"眼熟"}]}]}

You need to take out the w field in the json format and spell it into a result string for display

  • Get ws from the json array
  • ws is an array, the array element is object
  • cw is an array, the array element is object
  • w is string
  • Traverse from cw to get the w field

The preliminary implementation is as follows:

func RecResultJsonToPlain() {    var recResult string    var dat map[string]interface{}
    json.Unmarshal([]byte(json_str), &dat)    if v, ok := dat["ws"]; ok {
        ws := v.([]interface{})        for i, wsItem := range ws {
            wsMap := wsItem.(map[string]interface{})            if vCw, ok := wsMap["cw"]; ok {
                cw := vCw.([]interface{})                for i, cwItem := range cw {
                    cwItemMap := cwItem.(map[string]interface{})                    if w, ok := cwItemMap["w"]; ok {
                        recResult = recResult + w.(string)
                    }
                }
            }
        }
    }
    fmt.Println(recResult)
}

In this way, it is a bit troublesome to convert types layer by layer and then obtain elements. Since it is a known json data structure, you can define the structure and then parse it.

type CWItem struct {
    SC int32  `json:"sc"`
    W  string `json:"w"`}type WSItem struct {
    CW []CWItem}type IatResult struct {
    SN int32    `json:"sn"`
    LS bool     `json:"ls"`
    BG int32    `json:"bg"`
    ED int32    `json:"ed"`
    WS []WSItem `json:"ws"`}

NoteThe first letter of the variable name must be capitalized when defining it. You can also use tools to automatically generate definitions https://mholt.github.io/json-to -go/; The tool generated is quite beautiful:

type AutoGenerated struct {
    Sn int `json:"sn"`
    Ls bool `json:"ls"`
    Bg int `json:"bg"`
    Ed int `json:"ed"`
    Ws []struct {
        Bg int `json:"bg"`
        Cw []struct {
            Sc int `json:"sc"`
            W string `json:"w"`
        } `json:"cw"`
    } `json:"ws"`
}
func RecResultJsonToPlain(jsonResult []byte)(recPlainResult string)  {    var r IatResult
    json.Unmarshal(jsonResult, &r)    for _, wsItem := range r.WS {        for _, cwItem := range wsItem.CW {
            recPlainResult = recPlainResult + cwItem.W
        }
    }    return recPlainResult
}

The above elements have json:"sn"mandatory description, so if you only need to get the corresponding elements, other elements It’s okay not to define it. Another kind of data is that the elements in the array are still arrays, and the last array contains number or string type. You need to rewrite a function. The data is as follows. Get the elements in [21,1]

{"Asks": [[21, 1], [22, 1]] ,"Bids": [[20, 1], [19, 1]]}

Search for a piece of code as follows, re-implementing UnmarshalJSON

package mainimport (    "encoding/json"    "fmt")type Message struct {
    Asks []Order `json:"Bids"`
    Bids []Order `json:"Asks"`}type Order struct {
    Price  float64
    Volume float64}func (o *Order) UnmarshalJSON(data []byte) error {    var v [2]float64    if err := json.Unmarshal(data, &v); err != nil {        return err    }
    o.Price = v[0]
    o.Volume = v[1]    return nil}func main() {
    b := []byte(`{"Asks": [[21, 1], [22, 1]] ,"Bids": [[20, 1], [19, 1]]}`)    var m Message    if err := json.Unmarshal(b, &m); err != nil {
        fmt.Println(err)        return    }
    fmt.Printf("%#v\n", m)}

For more golang related technical articles, please visit the go language column!

The above is the detailed content of How to parse json format in golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete