我正在尝试使用他们的开放 API 获取特定 Subreddit 的热门提交列表:
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
)
const api_endpoint = "http://www.reddit.com/r/%s/top.json?t=all&limit=100"
func main() {
// Get console argument 'subreddit' and format the API endpoint URL.
subreddit := os.Args[1]
top_by_subreddit_endpoint := fmt.Sprintf(api_endpoint, subreddit)
// Hit the API service.
response, err := http.Get(top_by_subreddit_endpoint)
if err != nil {
//Perror(err)
} else {
defer response.Body.Close()
content, err := ioutil.ReadAll(response.Body)
if err != nil {
//Perror(err)
} else {
var top_submissions Submission
json.Unmarshal(content, &top_submissions)
}
}
}
type ByCreated []Submission
func (a ByCreated) Len() int { return len(a) }
func (a ByCreated) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByCreated) Less(i, j int) bool { return a[i].Created < a[j].Created }
type Submission struct {
Domain string `json:"domain"`
BannedBy string `json:"banned_by"`
MediaEmbed string `json:"media_embed"`
Subreddit string `json:"subreddit"`
SelftextHtml string `json:"selftext_html"`
Selftext string `json:"selftext"`
Likes bool `json:"likes"`
SecureMedia string `json:"secure_media"`
LinkFlairText string `json:"link_flair_text"`
Id string `json:"id"`
Gilded int `json:"gilded"`
SecureMediaEmbed string `json:"secure_media_embed"`
Clicked bool `json:"clicked"`
Stickied bool `json:"stickied"`
Author string `json:"author"`
Media string `json:"media"`
Score int `json:"score"`
ApprovedBy string `json:"approved_by"`
Over18 bool `json:"over_18"`
Hidden bool `json:"hidden"`
Thumbnail string `json:"thumbnail"`
SubredditId string `json:"subreddit_id"`
Edited int `json:"edited"`
LinkFlairCssClass string `json:"link_flair_css_class"`
AuthorFlairCssClass string `json:"author_flair_css_class"`
Downs int `json:"downs"`
Saved bool `json:"saved"`
IsSelf bool `json:"is_self"`
Permalink string `json:"permalink"`
Name string `json:"name"`
Created int `json:"created"`
Url string `json:"url"`
AuthorFlairText string `json:"author_flair_text"`
Title string `json:"title"`
CreatedUtc int `json:"created_utc"`
Ups int `json:"ups"`
NumComments int `json:"num_comments"`
Visited bool `json:"visited"`
NumReports string `json:"num_reports"`
Distinguished string `json:"distinguished"`
}
不幸的是,这不起作用,因为 actual submission list is nested inside the response .如何将数据 json 数组(位于 children 元素内)解码为 Submission 结构类型的数组?
{
"kind": "Listing",
"data": {
"modhash": "1wcy5kngm9408522707f8e319ca825af342a5b3c460ca7c928",
"children": [
{
"kind": "t3",
"data": {
"domain": "self.Smite",
"banned_by": null,
"media_embed": {},
"subreddit": "Smite",
"selftext_html": "<!-- SC_OFF --><div class=\"md\"><p>Hello Smite community - how&#39;s it going? My name is Steve, but you can just call me Proto. I&#39;m a forum moderator and content creator for Beyond Entertainment - a site which specializes in gaming news surrounding competitive console gaming and all around video games news. I&#39;ve been around competitive gaming since 2007 back in the Halo 2 MLG days and have been hooked ever since. I&#39;m not here to talk about myself though - and although I&#39;m not a Smite player - I&#39;m here to talk about a company who is becoming involved with the Smite community that goes by the name Bonafide Boarding <a href=\"https://twitter.com/LiveBNFD\">https://twitter.com/LiveBNFD</a> </p>\n\n<p>Now you might be asking yourself why am I writing this? First, these 2 tweets drew my attention in regards to Bonafide Boarding <a href=\"https://twitter.com/BonafideBCC\">https://twitter.com/BonafideBCC</a> - as well as Billy and Brad - working with people in the competitive Smite community </p>\n\n<p><a href=\"https://twitter.com/LiveBNFD/status/441044741699149825\">https://twitter.com/LiveBNFD/status/441044741699149825</a> </p>\n\n<p><a href=\"https://twitter.com/HiRezNabil\">https://twitter.com/HiRezNabil</a> (pictures with Brad under this Twitter user&#39;s photos - Brad confirmed in the AGL Facebook cover photo as well just for verification) </p>\n\n<p>Well - I&#39;m writing this because the owners of the Bonafide Boarding Clothing company, Brad Weir and Billy Lutz <a href=\"https://twitter.com/MrBillyLutz\">https://twitter.com/MrBillyLutz</a> have past experience in competitive gaming. including running their own league of Halo tournaments in 2012 and 2013. However, it&#39;s not a good past - and to put it as blunt as possible - the two together are frauds who stole money from the Halo community and owe professional Halo players thousands of dollars from their Halo events - at the time known as AGL (Arena Gaming League) <a href=\"https://www.facebook.com/ArenaGamingLeague\">https://www.facebook.com/ArenaGamingLeague</a> (Brad Weir is in the cover photo, on the right, in the red t shirt interviewing the person on the left) </p>\n\n<p>Brad and Billy had their first AGL Halo event in August of 2012 - and in 2013 is when the problems began. While there is a lot more to talk about then what can be posted here, I will basically go into how AGL ended and how Halo players were scammed out of thousands of dollars in owed prize money - and to this day, no one has received any money from AGL, Brad or Billy for most of the 2013 AGL Halo tournaments. </p>\n\n<p>AGL had announced an event to held in Indianapolis, Indiana on November 1-3, 2013 called the &quot;AGL 10K&quot;. It was made out to be their biggest event yet - held at a brand new LAN center and promising the most prize money at any AGL event thus far at the time. However, just days before the event was scheduled to take place, it was cancelled as noted here with a direct quote from AGL/Brad in the article below </p>\n\n<p><a href=\"http://teambeyond.net/agl-10k-cancelled/\">http://teambeyond.net/agl-10k-cancelled/</a> </p>\n\n<p>This also led to players not being able to get refunds for their team passes which many had already purchased for the event (note the dates on the tweets shown below) </p>\n\n<p><a href=\"https://twitter.com/jCreelz/status/394116351402737664\">https://twitter.com/jCreelz/status/394116351402737664</a> </p>\n\n<p><a href=\"https://twitter.com/Ninja_Invictus/status/393922514247643136\">https://twitter.com/Ninja_Invictus/status/393922514247643136</a> </p>\n\n<p>Not long after this event was cancelled, AGL completely shut down, seemingly out of nowhere - confirmed in this forum post by Brad himself on the Beyond Entertainment forums </p>\n\n<p><a href=\"http://teambeyond.net/forum/index.php?/topic/2238-agl-closes-down-statement/page-50?p=108159#entry108159\">http://teambeyond.net/forum/index.php?/topic/2238-agl-closes-down-statement/page-50?p=108159#entry108159</a> </p>\n\n<p>Since AGL has shut down, there has been little to absolutely no contact from Brad, Billy, or anyone associated with AGL in terms of paying not only the professional players who are owed prize money, but commentators and staff from the event as well who were not paid and had no travel costs covered. </p>\n\n<p>The following are all tweets from professional Halo players who have still NEVER been paid by Brad Weir, Billy Lutz, or AGL as a whole. </p>\n\n<p><a href=\"https://twitter.com/MLGACE/statuses/408356773037232128\">https://twitter.com/MLGACE/statuses/408356773037232128</a> </p>\n\n<p><a href=\"https://twitter.com/FormaL_tK/statuses/408400562372108288\">https://twitter.com/FormaL_tK/statuses/408400562372108288</a> </p>\n\n<p><a href=\"https://twitter.com/Naded_MLG/statuses/426908120879607808\">https://twitter.com/Naded_MLG/statuses/426908120879607808</a> </p>\n\n<p><a href=\"https://twitter.com/xPROVERBx/statuses/426975901583425536\">https://twitter.com/xPROVERBx/statuses/426975901583425536</a> </p>\n\n<p><a href=\"https://twitter.com/enable_/status/426952260317220864\">https://twitter.com/enable_/status/426952260317220864</a> </p>\n\n<p><a href=\"https://twitter.com/BRIZZ_Legit/status/426959849729974272\">https://twitter.com/BRIZZ_Legit/status/426959849729974272</a> </p>\n\n<p>This recent tweet is also from someone who bought t shirts from Bonafide Boarding, Brad and Billy&#39;s clothing company, and it appears they were screwed as well. </p>\n\n<p><a href=\"https://twitter.com/shellyteachesk2/status/447432597288017920\">https://twitter.com/shellyteachesk2/status/447432597288017920</a> </p>\n\n<p>The reason I am writing all this is just to warn you guys as a community to not fall into the trap the Halo community fell into in 2013. Do not support these guys - and most importantly - do not give them your money. I have loved competitive gaming for a long time, and I want nothing more than to see it continue to grow. The last thing I want to see happen is what happened to the Halo community in 2013 at the hands of Brad Weir, Billy Lutz, and the AGL company as a whole. Brad, Billy, and Bonafide Boarding as a whole is nothing but a scam and these 2 owe a lot of people a lot of money. Hopefully you guys can take this to heart and not support these two scumbags who have still yet to pay thousands of dollars to people who rightfully won money in their tournaments. Thank you for reading. </p>\n\n<ul>\n<li>Proto</li>\n</ul>\n</div><!-- SC_ON -->",
"selftext": "Hello Smite community - how's it going? My name is Steve, but you can just call me Proto. I'm a forum moderator and content creator for Beyond Entertainment - a site which specializes in gaming news surrounding competitive console gaming and all around video games news. I've been around competitive gaming since 2007 back in the Halo 2 MLG days and have been hooked ever since. I'm not here to talk about myself though - and although I'm not a Smite player - I'm here to talk about a company who is becoming involved with the Smite community that goes by the name Bonafide Boarding https://twitter.com/LiveBNFD \n\nNow you might be asking yourself why am I writing this? First, these 2 tweets drew my attention in regards to Bonafide Boarding https://twitter.com/BonafideBCC - as well as Billy and Brad - working with people in the competitive Smite community \n\nhttps://twitter.com/LiveBNFD/status/441044741699149825 \n\nhttps://twitter.com/HiRezNabil (pictures with Brad under this Twitter user's photos - Brad confirmed in the AGL Facebook cover photo as well just for verification) \n\nWell - I'm writing this because the owners of the Bonafide Boarding Clothing company, Brad Weir and Billy Lutz https://twitter.com/MrBillyLutz have past experience in competitive gaming. including running their own league of Halo tournaments in 2012 and 2013. However, it's not a good past - and to put it as blunt as possible - the two together are frauds who stole money from the Halo community and owe professional Halo players thousands of dollars from their Halo events - at the time known as AGL (Arena Gaming League) https://www.facebook.com/ArenaGamingLeague (Brad Weir is in the cover photo, on the right, in the red t shirt interviewing the person on the left) \n\nBrad and Billy had their first AGL Halo event in August of 2012 - and in 2013 is when the problems began. While there is a lot more to talk about then what can be posted here, I will basically go into how AGL ended and how Halo players were scammed out of thousands of dollars in owed prize money - and to this day, no one has received any money from AGL, Brad or Billy for most of the 2013 AGL Halo tournaments. \n\nAGL had announced an event to held in Indianapolis, Indiana on November 1-3, 2013 called the \"AGL 10K\". It was made out to be their biggest event yet - held at a brand new LAN center and promising the most prize money at any AGL event thus far at the time. However, just days before the event was scheduled to take place, it was cancelled as noted here with a direct quote from AGL/Brad in the article below \n\nhttp://teambeyond.net/agl-10k-cancelled/ \n\nThis also led to players not being able to get refunds for their team passes which many had already purchased for the event (note the dates on the tweets shown below) \n\nhttps://twitter.com/jCreelz/status/394116351402737664 \n\nhttps://twitter.com/Ninja_Invictus/status/393922514247643136 \n\nNot long after this event was cancelled, AGL completely shut down, seemingly out of nowhere - confirmed in this forum post by Brad himself on the Beyond Entertainment forums \n\nhttp://teambeyond.net/forum/index.php?/topic/2238-agl-closes-down-statement/page-50?p=108159#entry108159 \n\nSince AGL has shut down, there has been little to absolutely no contact from Brad, Billy, or anyone associated with AGL in terms of paying not only the professional players who are owed prize money, but commentators and staff from the event as well who were not paid and had no travel costs covered. \n\nThe following are all tweets from professional Halo players who have still NEVER been paid by Brad Weir, Billy Lutz, or AGL as a whole. \n\nhttps://twitter.com/MLGACE/statuses/408356773037232128 \n\nhttps://twitter.com/FormaL_tK/statuses/408400562372108288 \n\nhttps://twitter.com/Naded_MLG/statuses/426908120879607808 \n\nhttps://twitter.com/xPROVERBx/statuses/426975901583425536 \n\nhttps://twitter.com/enable_/status/426952260317220864 \n\nhttps://twitter.com/BRIZZ_Legit/status/426959849729974272 \n\nThis recent tweet is also from someone who bought t shirts from Bonafide Boarding, Brad and Billy's clothing company, and it appears they were screwed as well. \n\nhttps://twitter.com/shellyteachesk2/status/447432597288017920 \n\nThe reason I am writing all this is just to warn you guys as a community to not fall into the trap the Halo community fell into in 2013. Do not support these guys - and most importantly - do not give them your money. I have loved competitive gaming for a long time, and I want nothing more than to see it continue to grow. The last thing I want to see happen is what happened to the Halo community in 2013 at the hands of Brad Weir, Billy Lutz, and the AGL company as a whole. Brad, Billy, and Bonafide Boarding as a whole is nothing but a scam and these 2 owe a lot of people a lot of money. Hopefully you guys can take this to heart and not support these two scumbags who have still yet to pay thousands of dollars to people who rightfully won money in their tournaments. Thank you for reading. \n\n- Proto",
"likes": true,
"secure_media": null,
"link_flair_text": null,
"id": "21dp8c",
"gilded": 0,
"secure_media_embed": {},
"clicked": false,
"stickied": false,
"author": "Proto__",
"media": null,
"score": 1038,
"approved_by": null,
"over_18": false,
"hidden": false,
"thumbnail": "",
"subreddit_id": "t5_2stl8",
"edited": 1395865323,
"link_flair_css_class": null,
"author_flair_css_class": null,
"downs": 274,
"saved": false,
"is_self": true,
"permalink": "/r/Smite/comments/21dp8c/a_warning_to_the_smite_community_bonafide/",
"name": "t3_21dp8c",
"created": 1395828838,
"url": "http://www.reddit.com/r/Smite/comments/21dp8c/a_warning_to_the_smite_community_bonafide/",
"author_flair_text": null,
"title": "A warning to the Smite community (Bonafide Boarding Clothing company)",
"created_utc": 1395800038,
"ups": 1312,
"num_comments": 200,
"visited": false,
"num_reports": null,
"distinguished": null
}
}],
}
}
}
最佳答案
再创建一些结构(就像您的 Submission 结构)来模仿 JSON 的确切形状。解码到最顶层结构之一,然后访问该结构的适当成员。
关于json - 使用 unmarshal 从响应中获取特定的 JSON 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23317191/
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
很好奇,就使用rubyonrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提
假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于
我正在尝试使用ruby和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t
我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h
我想为Heroku构建一个Rails3应用程序。他们使用Postgres作为他们的数据库,所以我通过MacPorts安装了postgres9.0。现在我需要一个postgresgem并且共识是出于性能原因你想要pggem。但是我对我得到的错误感到非常困惑当我尝试在rvm下通过geminstall安装pg时。我已经非常明确地指定了所有postgres目录的位置可以找到但仍然无法完成安装:$envARCHFLAGS='-archx86_64'geminstallpg--\--with-pg-config=/opt/local/var/db/postgresql90/defaultdb/po