JSON parsing of Golang entry

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

Interpretation

JSON is a lightweight data exchange language that is text-based and easy to read. Although JSON is a subset of JavaScript, JSON is a language-independent text format and uses some of the same habits as the C language family.
Other languages transferred to the children's shoes, especially the Android developer is unavoidable to use to JSON parsing work, and in Golang the operation of the JSON is very simple, the following details about the use of JSON parsing in Golang.
Description: The API used in the instance is fromhttp://gank.io/api

JSON format

{    "_id": "59e905da421aa90fe2f02bcf",  "createdAt": "2017-10-20T04:06:50.148Z",  "desc": "Hacktoberfest - open source 參與項目推薦",  "publishedAt": "2017-10-20T10:26:24.673Z",  "source": "web",  "type": "拓展资源",  "url": "https://github.com/WeiChiaChang/Daily-Digest-Collection/issues/11",  "used": true,  "who": "WesleyChang" }

Preparatory work

    • Driven
      Encoding/json//json Drive
      Net/http//Network Driver
    • struct
      General struct attribute naming rules in Golang you're free. It is possible to write the first letter case.
      If some fields in JSON are named differently than their own styles, you can add ' json: ' xxx ' after the field, and then parse the value of the corresponding jsonobject into the field of your own name. where "'" is not a single quotation mark, but a point of the English half-angle above the TAB key.
      The following example:
type GankMain struct {  Id          string `json:"_id"`  CreatedAt   time.Time `json:"createdAt"`  Desc        string `json:"desc"`  PublishedAt time.Time `json:"publishAt"`  Source      string `json:"source"`  Type        string `json:"type"`  Url         string `json:"url"`  Used        bool `json:"used"`  Who         string `json:"who"` }type Results struct {   Error   bool `json:"error"`  Results []GankMain `json:"results"` }
    • Get JSON over the network
//拿到resp对象resp, err := http.Get("http://gank.io/api/data/all/10/1")//判断是否出错if err != nil {   return  }//判断是否请求成功if resp.StatusCode != http.StatusOK {   resp.Body.Close()   return nil, fmt.Errorf("请求出错:%s", resp.Status)}

At this point, the JSON object has been obtained, and it is resp. Body () object, the following begins the parsing operation.

Start parsing

Ready to receive the parsed result object

var result Results

One line of code is done

 eror := json.NewDecoder(resp.Body).Decode(&result)

So we got the result.
Here is a more interesting place, that is, the decode function passed the result returned by the error, here is the attribute of C, after the argument is assigned in the function, the external result object is already assigned value. For Java programmers to understand, remember.
Print to see the results as follows:

&{false [{59ec7dc4421aa90fe50c018f 2017-10-22 19:15:16.956 +0000 UTC "Fools" Jedi Survival movie version? A group of murderers to eat chicken, fools show you Understand "escape ice Island" 0001-01-01 00:00:00 +0000 UTC chrome break video Http://www.bilibili.com/video/av15581509/true LHF} { 59EFE9FB421AA90FE72535C1 2017-10-25 09:33:47.784 +0000 UTC comparable to Ali plugin for Android Studio plug-in collection (IDE Universal) (ON) 0001-01-01 00:00:00 + 0000 UTC Web Android https://mp.weixin.qq.com/s?__biz=MzIwMzYwMTk1NA==&mid=2247487640&idx=1&sn= 3752d389f908a6116341a03e6f3c6730 true Chen Yuming} {59EFF4AD421AA90FEF2034CB 2017-10-25 10:19:25.884 +0000 UTC android Open source Frame List-- Hundred frame leaderboards 0001-01-01 00:00:00 +0000 UTC web Android https://github.com/ShaunSheep/Android_100_TOP-Projects true Chaofun} { 59eff996421aa90fe2f02bf1 2017-10-25 10:40:22.6 +0000 UTC Wedding big screen Interactive, invitation one-stop solution 0001-01-01 00:00:00 +0000 UTC Web Front end Https://git hub.com/iammapping/wedding true Xin Faru put} {59f0010c421aa90fef2034cc 2017-10-25 11:12:12.416 +0000 UTC MVVM + FLUX reactive FAC Ade Viewkit 0001-01-01 00:00:00 +0000 UTC Chrome IOS https://github.com/geekaurora/ReactiveListviewkit true Daimajia} {59f0054a421aa90fe2f02bf4 2017-10-25 11:30:18.697 +0000 UTC 2017-10-25 0001-01-01 00:00:00 +00 UTC Chrome Benefit http://7xi8d6.com1.z0.glb.clouddn.com/20171025112955_lmesMu_katyteiko_25_10_2017_11_29_43_270. JPEG true Code home} {59f00605421aa90fef2034cd 2017-10-25 11:33:25.66 +0000 UTC burp Suite opens up a new database to get through the API interface to quickly assist penetration testing. 0001-01-01 00:00:00 +0000 UTC Chrome Expand Resources Https://github.com/vulnersCom/burp-vulners-scanner True code home} { 59f00673421aa90fe2f02bf5 2017-10-25 11:35:15.934 +0000 UTC long enough for the Shadow effect. 0001-01-01 00:00:00 +0000 UTC Chrome Android Https://github.com/florent37/LongShadow true code home} { 59EB735F421AA90FEF2034B1 2017-10-22 00:18:39.652 +0000 UTC cost 1 trillion yuan of the world's tallest building, high 4-kilometer live 1 million people, 2050 completed 0001-01-01 00:00:00 +0000 UTC Chrome break video Http://www.bilibili.com/video/av15580072/true LHF} {59edb49b421aa90fe50c0197 2017-10-23 17:21:31.325 + 0000 UTC Front-end weekly checklist 36th: Deep Vue 2.5 type enhancement, puppeteer end-to-end testing, PayPal cross-domain suite 0001-01-01 00:00:00 +0000 UTC web front end Https://zhuanlan.zh ihu.com/p/30379534 truE Wang invites the Moon Bear (Chevalier)}]} 

Add

The above example uses the direct read stream JSON operation, json.NewDecoder(r io.Reader) if you need to manipulate the string directly, you can use thejson.Unmarshal(data []byte, v interface{})
Converts a string into a byte array, passing in the parsed struct object;

Reference documents

Wikipedia Json:https://zh.wikipedia.org/wiki/json
Go language programming Xu Xiwei and so on the first edition of the People's post and telecommunications publishing house 290p.

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.