Go language conversion

If you don’t know the types in JSON, you won’t be able to build structures.

package main

import (
	"encoding/json"
	"fmt"
)

type Data struct {
	Status  int    `json:"status"`
	Msg   int    `json:"msg"`
}


func main(a) {
	msg := "{\"status\":200, \"msg\":18}"
	var data Data
	if err := json.Unmarshal([]byte(msg), &data); err == nil {
		fmt.Println(data.Status)
	} else {
		fmt.Println(err)
	}
}

Copy the code

The encode\json package also provides another way to parse JSON data.

Encoding \json package uses:

Map [string] interface {} Stores JOSN objects. [] interface stores an array of JOSNCopy the code

Js.unmarshl will store any valid JSON data into a value of type Interface {}. By using the null interface type we can store any value, but using this type as a value requires a type assertion first.

Example code:

jsonData := []byte(`{"Name":"Eve","Age":6,"Parents":["Alice","Bob"]}`)

var v interface{}
json.Unmarshal(jsonData, &v)
data := v.(map[string]interface{})

for k, v := range data {
    switch v := v.(type) {
    case string:
        fmt.Println(k, v, "(string)")
    case float64:
        fmt.Println(k, v, "(float64)")
    case []interface{}:
        fmt.Println(k, "(array):")
        for i, u := range v {
            fmt.Println("", i, u)
        }
    default:
        fmt.Println(k, v, "(unknown)")}}Copy the code

Parse the data stream with a Decoder

This is all JSON data parsed using UnMarshall. If the JSON data is streamed to an open file or HTTP request body (both are implemented by IO. We do not need to call encode/ JSON package UnMarshall after reading the JSON data, the Decode method provided by the package can complete the operation of reading the data stream, parsing the JSON data and filling the variables.

// This example uses a Decoder to decode a stream of distinct JSON values.
func ExampleDecoder(a) {
    const jsonStream = ` {"Name": "Ed", "Text": "Knock knock."} {"Name": "Sam", "Text": "Who's there?" } {"Name": "Ed", "Text": "Go fmt."} {"Name": "Sam", "Text": "Go fmt who?" } {"Name": "Ed", "Text": "Go fmt yourself!" } `
    type Message struct {
        Name, Text string
    }
    dec := json.NewDecoder(strings.NewReader(jsonStream))
    for {
        var m Message
        if err := dec.Decode(&m); err == io.EOF {
            break
        } else iferr ! =nil {
            log.Fatal(err)
        }
        fmt.Printf("%s: %s\n", m.Name, m.Text)
    }
    // Output:
    // Ed: Knock knock.
    // Sam: Who's there?
    // Ed: Go fmt.
    // Sam: Go fmt who?
    // Ed: Go fmt yourself!
}
Copy the code