Golang--json using Notes

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

In JSON encoding, the most troublesome is the JSON array, the following document I encountered in the JSON coding problems and the source of the solution:

If you want to package this format:

{"Key": 222, "msg": {"ed": "AAA", "GF": "23.45", "RS": "All"}, "Status": 1}

The code is as follows:

Package Mainimport ("Encoding/json", "FMT") func main () {t: = Make (map[string]interface{}) t["ed"] = "AAA" t["rs"] = "All" t[" GF "] =" 23.45 "Res: = Make (map[string]interface{}) res[" status "] = 1res[" key "] = 222res[" msg "] = tbody, err: = json. Marshal (RES) if err! = Nil {fmt. PRINTLN (ERR) return} else {fmt. Println (String (Body))}}



If you want to package the following format:

{"Key": 222, "MSG": [{"ed": "AAA", "GF": "23.45", "rs": "%"}], "Status": 1}

The code is as follows:

Package Mainimport ("Encoding/json", "FMT") func main () {var rbody []map[string]interface{}t: = Make (Map[string]interface  {}) t["ed"] = "AAA" t["rs"] = "" t["GF"] = "23.45" rbody = append (rbody, t) Res: = Make (map[string]interface{}) res["status"] = 1res["key"] = 222res["msg"] = rbodybody, err: = json. Marshal (RES) if err! = Nil {fmt. PRINTLN (ERR) return} else {fmt. Println (String (Body))}}


In parsing the JSON structure, the most troublesome is parsing the JSON array, such as parsing:

{"Key": 222, "MSG": [{"ed": "AAA", "GF": "23.45", "rs": "%"}], "Status": 1}

The code is as follows:

Package Mainimport ("Encoding/json" "FMT") type TT struct {Key    intmsg    []msgstatus int}type msg struct {Ed Stringrs STRINGGF String}func Main () {Tests: = Tt{}body: = ' {"Key": 222, "MSG": [{"ed": "AAA", "GF": "23.45", "RS": "+"}], "Status": 1} ' Jsonerr: = json. Unmarshal ([]byte (body), &tests)/*[]byte () is a string that can be cast into the city byte*/if Jsonerr! = nil {fmt. Println (Jsonerr) return}fmt. PRINTLN (Tests. Key) fmt. PRINTLN (Tests. Msg[0]. ED)}



Related Article

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.