How [series] Go parse JSON data?

Outline

Recent demand fell into the pit, just climb to assess schedule a serious problem, the following three figures are in line with prevailing mood.

On the demand

Estimated schedule

Began to dry

Why is this so, I briefly summarized below:

  • Docking with third parties.
  • Cross-docking team.
  • For the first time to do the project with Go.
  • Business Process did not record clearly on the schedule (pit).
  • Adjust the schedule (pit) not demand after adjustment.

With this experience, the latter on how to assess the schedule and you can also going on.

Ado, into the theme today.

Today to share how to parse JSON data Go, contains three cases, strongly typed resolution, weak type resolution, return uncertain structure and so on.

JSON structure

For example, home phone requested interface, JSON returns the following data:

{
    "resultcode": "200",
    "reason": "Return Successd!",
    "result": {
        "province": "浙江",
        "city": "杭州",
        "areacode": "0571",
        "zip": "310000",
        "company": "中国移动",
        "card": ""
    }
}

The idea is this:

1. First json turn into struct.

2. Then json.Unmarshal()you can.

json turn struct, own handwriting too much trouble, there are many online tools can be used directly, I use this:

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

Affixed to the left rear json generates a struct.

Using the code to achieve:

type MobileInfo struct {
    Resultcode string `json:"resultcode"`
    Reason     string `json:"reason"`
    Result     struct {
        Province string `json:"province"`
        City     string `json:"city"`
        Areacode string `json:"areacode"`
        Zip      string `json:"zip"`
        Company  string `json:"company"`
        Card     string `json:"card"`
    } `json:"result"`
}

func main() {
    jsonStr := `
        {
            "resultcode": "200",
            "reason": "Return Successd!",
            "result": {
                "province": "浙江",
                "city": "杭州",
                "areacode": "0571",
                "zip": "310000",
                "company": "中国移动",
                "card": ""
            }
        }
    `

    var mobile MobileInfo
    err := json.Unmarshal([]byte(jsonStr), &mobile)
    if err != nil {
        fmt.Println(err.Error())
    }
    fmt.Println(mobile.Resultcode)
    fmt.Println(mobile.Reason)
    fmt.Println(mobile.Result.City)
}

Output:

200
Return Successd!
杭州

Perfect resolution.

To this problem is not over, ponder these questions:

If json format data type unsure how to do?

If the data result json format parameter is not fixed how to do?

The idea is this:

Open-source library to find on github, ha ha, I am using is this:

https://github.com/mitchellh/mapstructure

Let's learn together under first solve the first problem, the data type unsure how to do?

Define a string type of resultcode, json but returned int type resultcode.

There are ways to see the document type resolution of a weak WeakDecode(), let's try:

type MobileInfo struct {
    Resultcode string `json:"resultcode"`
}

func main() {
    jsonStr := `
        {
            "resultcode": 200
        }
    `

    var result map[string]interface{}
    err := json.Unmarshal([]byte(jsonStr), &result)
    if err != nil {
        fmt.Println(err.Error())
    }

    var mobile MobileInfo
    err = mapstructure.WeakDecode(result, &mobile)
    if err != nil {
        fmt.Println(err.Error())
    }

    fmt.Println(mobile.Resultcode)
}

Output:

200

The first issue has been resolved.

And then solve the second problem, result in parameters not fixed how to do?

This would not have the above example, the example provided by the official look Example (EmbeddedStruct).

type Family struct {
    LastName string
}
type Location struct {
    City string
}
type Person struct {
    Family    `mapstructure:",squash"`
    Location  `mapstructure:",squash"`
    FirstName string
}

func main() {
    input := map[string]interface{}{
        "FirstName": "Mitchell",
        "LastName":  "Hashimoto",
        "City":      "San Francisco",
    }

    var result Person
    err := mapstructure.Decode(input, &result)
    if err != nil {
        panic(err)
    }

    fmt.Println(result.FirstName)
    fmt.Println(result.LastName)
    fmt.Println(result.City)
}

Output:

Mitchell
Hashimoto
San Francisco

Using mapstructure package, struct tag identifies Do not write json, write mapstructure.

Other cases to explore their own right, such as: Example (Tags).

go-gin-api series

Published 184 original articles · won praise 141 · Views 350,000 +

Guess you like

Origin blog.csdn.net/sinat_27535209/article/details/103834769