Home  >  Article  >  Backend Development  >  Golang json garbled solution

Golang json garbled solution

尚
Original
2019-12-13 13:54:095770browse

Golang json garbled solution

Golang json garbled code can be solved by using the "encoding/json" package in the golang program to encode and decode the json object.

Recommended: golang tutorial

golang encodes and decodes json objects Example:

package main
import (
    "fmt"
    "encoding/json"
)
func main() {
    // json encode
    j1 := make(map[string]interface{})
    j1["name"] = "PHP中文网"
    j1["url"] = "https://www.php.cn/"
    js1, err := json.Marshal(j1)
    if err != nil {
        panic(err)
    }
    println(string(js1))
    // json decode
    j2 := make(map[string]interface{})
    err = json.Unmarshal(js1, &j2)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%#v\n", j2)
}

golang standard library encoding/json is used To process json data, it has two sets of functions or methods to process json data.

Golang json garbled solution

Encoding function

Encoding function: func Marshal(v interface{}) ([]byte, error)

Encoding rules: Recursively traverse v. A value in v implements the Marshaler interface and calls the MarshalJSON method to encode. If there is no such method but encoding.TextMarshl is implemented, use MarshalText to encode.

Decoding function

Decoding function: func Unmarshal(data []byte, v interface{}) error

data is a JSON data

v is Pointer to store decoded data

error error type returned

The above is the detailed content of Golang json garbled solution. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn