Golang-从Twitch TV RESTful服务解析JSON字符串数组

I've been working on parsing a JSON object that I retrieve through an HTTP GET request using Go's built in HTTP library. I initially tried using the default JSON library in Go in order to do this, but I was having a difficult time (I am a novice in Go still). I eventually resorted to using a different library and had little trouble after that, as shown below:

package main

import (
    "github.com/antonholmquist/jason"
    "fmt"
    "net/http"
)

func main() {
    resp, err := http.Get("http://tmi.twitch.tv/group/user/deernadia/chatters")
    if nil != err {
        panic(err)
    }
    defer resp.Body.Close()
    body, err := jason.NewObjectFromReader(resp.Body)

    chatters, err := body.GetObject("chatters")
    if nil != err {
        panic(err)
    }

    moderators, err := chatters.GetStringArray("moderators")
    if nil != err {
        panic(err)
    }

    for _, moderator := range moderators {
        fmt.Println(moderator)
    }
}

Where github.com/antonholmquist/jason corresponds to the custom JSON library I used.

This code produces something similar to the following output when run in a Linux shell (the RESTful service will update about every 30 seconds or so, which means the values in the JSON object will potentially change):

antwan250
bbrock89
boxception22
cmnights
deernadia
fartfalcon
fijibot
foggythought
fulc_
h_ov
iceydefeat
kingbobtheking
lospollogne
nightbot
nosleeptv
octaviuskhan
pateyy
phosphyg
poisonyvie
shevek18
trox94
trox_bot
uggasmesh
urbanelf
walmartslayer
wift3

And the raw JSON looks similar to this (with some of the users removed for brevity):

{
  "_links": {},
  "chatter_count": 469,
  "chatters": {
    "moderators": [
      "antwan250",
      "bbrock89",
      "boxception22",
      "cmnights",
      "deernadia",
      "fartfalcon",
      "fijibot",
      "foggythought",
      "fulc_",
      "h_ov",
      "iceydefeat",
      "kingbobtheking",
      "lospollogne",
      "nightbot",
      "nosleeptv",
      "octaviuskhan",
      "pateyy",
      "phosphyg",
      "poisonyvie",
      "shevek18",
      "trox94",
      "trox_bot",
      "uggasmesh",
      "urbanelf",
      "walmartslayer",
      "wift3"
    ],
    "staff": [
      "tnose"
    ],
    "admins": [],
    "global_mods": [],
    "viewers": [
      "03xuxu30",
      "0dominic0",
      "3389942",
      "812mfk",
      "910dan",
      "aaradabooti",
      "admiralackbar99",
      "adrian97lol",
      "aequitaso_o",
      "aethiris",
      "afropigeon",
      "ahhhmong",
      "aizaix",
      "aka_magosh",
      "akitoalexander",
      "alex5761",
      "allenhei",
      "allou_fun_park",
      "amilton_tkm",
      "... more users that I removed...",
      "zachn17",
      "zero_x1",
      "zigslip",
      "ziirbryad",
      "zonato83",
      "zorr03body",
      "zourtv"
    ]
  }
}

As I said before, I'm using a custom library hosted on Github in order to accomplish what I needed, but for the sake of learning, I'm curious... how would I accomplish this same thing using Go's built in JSON library?

To be clear, what I'd like to do is be able to harvest the users from each JSON array embedded within the JSON object returned from the HTTP GET request. I'd also like to be able to get the list of viewers, admins, global moderators, etc., in the same way, but I figured that if I can see the moderator example using the default Go library, then reproducing that code for the other user types will be trivial.

Thank you in advance!

doubian0284
doubian0284 使用encoding/json,您必须定义具有正确字段的结构类型(如果代码中的字段与json字段名称不匹配,则需要定义json字段标签),声明该结构类型的变量,然后将指针传递给该变量到json.Unmarshal函数以及字节切片形式的json。从一些简单示例的Unmarshal函数开始(有关json,请参阅godoc)。
4 年多之前 回复

1个回答

If you want to unmarshal moderators only, use the following:

var v struct {
    Chatters struct {
        Moderators []string
    }
}
if err := json.Unmarshal(data, &v); err != nil {
    // handle error
}
 for _, mod := range v2.Chatters.Moderators {
    fmt.Println(mod)
}

If you want to get all types of chatters, use the following:

var v struct {
    Chatters map[string][]string
}
if err := json.Unmarshal(data, &v); err != nil {
    handle error
}
for kind, users := range v1.Chatters {
    for _, user := range users {
        fmt.Println(kind, user)
    }
}

run the code on the playground

donglin4636
donglin4636 完善! 非常感谢!
4 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问