Golang basic knowledge of the Encoding/json package

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Golang JSON of basic knowledge

Brief introduction

JSON (JavaScript Object Notation) is a lightweight data interchange format. You can go to json.org to see a clear definition of the JSON standard. The JSON package is the official Go Language pack, followed by an open source implementation of the JSON packages analysis.

Encoding

Func Marshal (v interface{}) ([]byte, error)

Basic type

Bolb, _: = json. Marshal (True) fmt. Println (String (Bolb)) IntB, _: = json. Marshal (1) fmt. Println (String (IntB)) FLTB, _: = json. Marshal (2.34) fmt. Println (String (FLTB))

Output


True
1
2.34
"Gopher"

Serialization of custom types

Type Response1 struct {Page   intfruits []string}//the JSON package can automatically encode your//custom data types. It would only include exported//fields in the encoded output and would by default//use those names as the JSON keys.res1d : = &response1{page:   1,fruits: []string{"Apple", "peach", "pear"}}res1b, _: = json. Marshal (RES1D) fmt. Println (String (res1b))

Only the externally accessible fields can be serialized into JSON.

Data structures that can be rendered in JSON form can be encode:

Because JSON objects only support strings for Key,go map types must be in the form of map[string]t

Channel, complex and function cannot be encode

The data structure of the loop does not support

The pointer is encode by the value pointed to

Decoding

Func unmarshal (data []byte, v interface{}) Errorb: = []byte (' {"Name": "Bob", "Food": "Pickle"} ') var m messageerr: = json. Unmarshal (b, &m)

Deserialization automatically ignores fields that are not externally accessible or missing fields in the structure

Using interface{} to process common JSON

B: = []byte (' {' "Name": "Wednesday", "Age": 6, "parents": ["Gomez", "Morticia"]} ') var f interface{}err: = json. Unmarshal (b, &f) b: = []byte (' {' "Name": "Wednesday", "Age": 6, "parents": ["Gomez", "Morticia"]} ') var f interface{}err: = json. Unmarshal (b, &f) if err! = Nil {panic (err)}m: = f. (map[string]interface{}) for k, V: = range m {Switch VV: = V. (type) {C ASE String:fmt. Println (k, ' is String ', vv) case int:fmt. Println (K, "is Int.", VV) case []INTERFACE{}:FMT. Println (K, "is a array:") for I, U: = Range VV {fmt. Println (i, u)}default:fmt. Println (K, "is of a type I don ' t know how to Handle")}}

Streaming encoders and decoders

Package Mainimport (    "Encoding/json"    "Log" "    OS") Func main () {dec: = json. Newdecoder (OS. Stdin) ENC: = json. Newencoder (OS. Stdout) for {    var v map[string]interface{}    If err: = Dec. Decode (&V); Err! = Nil {        log. PRINTLN (Err)        return    } for    k: = Range v {        if k! = "Name" {            Delete (V, k)}    }    If err: = E nc. Encode (&V); Err! = Nil {        log. PRINTLN (Err)    }}}

See:

http://blog.golang.org/json-and-gohttps://golang.org/pkg/encoding/json/#pkg-examples

Note:

This series is not a chatty Package API guide, only included in the author's view of the most common use, the protest is invalid.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.