dongxie2749 2015-12-21 03:48
浏览 69
已采纳

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!

  • 写回答

1条回答 默认 最新

  • douyangqian5243 2015-12-21 03:57
    关注

    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)
        }
    }
    

    <kbd>run the code on the playground</kbd>

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?