How does Golang parse and generate json

  • 2020-11-03 22:23:57
  • OfStack

JSON(Javascript Object Notation) is a lightweight data exchange language that is text-based, self-descriptive and easy to read. Although JSON is a subset of JavaScript, JSON is a language-independent text format and follows some habits similar to those of the C language family. The biggest difference between JSON and XML is that XML is a complete markup language, while JSON is not. JSON is smaller, faster, and easier to parse than XML, as well as the browser's built fast parsing support, making it more suitable for network data transfer.

Golang's built-in JSON parsing library, encoding/json, can be used to serialize structured data into json strings or parse the data we want from json strings.

1. The analytic json

Give a complex json string containing an array whose elements are json objects. We need to extract a field value from the first element of the array. Any other resolution can be referenced in the code below.


package main

import (
  "encoding/json"
  "fmt"
)

func main() {
    jsonStr := []byte(`{"uin":1589276509,"feedID":10000,"videos":[{"picture":"http://qqpublic.qpic.cn/avatar.jpg","duration":"839"}]}`)
    var jsonMap map[string]interface{}
    if err := json.Unmarshal(jsonStr, &jsonMap); err!=nil {
      fmt.Printf("json decode failed, err=%v", err)
      return
    }
    value, ok:=jsonMap["videos"]
    fmt.Printf("value=%#v\n", value)
    if ok {
        sliceValue, ok := value.([]interface{})
        if ok {
            mapValue, ok := sliceValue[0].(map[string]interface{})
            if ok {
                duration, ok := mapValue["duration"]
                if ok {
                    fmt.Printf("d=%v,type=%T\n",duration,duration)
                }
            }
        }
    }
}

Program output:

[

value=[]interface {}{map[string]interface {}{"picture":"http://qqpublic.qpic.cn/avatar.jpg", "duration":"839"}}
d=839,type=string

]

When parsing the json string, note the following:
(1) The correspondence between Go type and JSON type is as follows:

[

map[string]interface{} represents the JSON object
[]interface{} represents the JSON array
bool stands for JSON booleans
float64 stands for JSON numbers
string stands for JSON strings
nil stands for JSON null

]

2. Generate json

Suppose we have the following class (structure) student and its instance object st, and serialize it to json, the concrete implementation is as follows:


package main

import (
  "encoding/json"
  "fmt"
)

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

type Class struct {
  Name string
  Grade int
}

func main() {
// instantiation 1 Three data structures for generation json string 
  stu := Stu{
    Name: " zhang 3",
    Age: 18,
    sex: " male ",
  }

  // Pointer to the variable 
  cla := new(Class)
  cla.Name = "1 class "
  cla.Grade = 3
  stu.Class=cla

  //Marshal When the failure err!=nil
  jsonStu, err := json.Marshal(stu)
  if err != nil {
    fmt.Println(" generate json String error ")
  }

  //jsonStu is []byte Type, convert to string Type for easy viewing 
  fmt.Println(string(jsonStu))
}

Program output results:

[

{" name ":" 3 ", "Age" : 18, "class" : {" Name ":" 1 ", "Grade" : 3}}

]

As you can see from the above code:

(1) As long as it is an exportable member (variable uppercase), it can be converted to json. Since the member variable sex is not exportable, it cannot be converted to json.

(2) If the variable is labeled with json, such as next to Name json:"name" , then the converted json key will use the label "name", otherwise take the field name as key, such as "Age";

(3) Pointer variable, which is automatically converted to the value it points to during encoding, such as Class variable;

(4) The json string after serialization is a pure string.

The above is Golang how to parse and generate json details, more golang parse, generate json information please pay attention to other related articles on this site!


Related articles: