你好,我尝试将来自 api.nal.usda.gov/ndb 的 JSON 响应解码为结构,但它总是返回空:
{ []}
示例 JSON:
{
"list": {
"q": "butter",
"sr": "28",
"ds": "any",
"start": 0,
"end": 50,
"total": 4003,
"group": "",
"sort": "r",
"item": [
{
"offset": 0,
"group": "Branded Food Products Database",
"name": "BLUE BUNNY, PEANUT BUTTER PANIC, ICE CREAM, POWERFUL PEANUT BUTTER ICE CREAM CHARGED WITH PEANUT BUTTER AND FUDGE SAUCES AND OVERLOADED WITH PEANUT BUTTER CUPS, UPC: 070640034086",
"ndbno": "45011419",
"ds": "BL"
},
{
"offset": 1,
"group": "Branded Food Products Database",
"name": "BLUE BUNNY, ICE CREAM, PEANUT BUTTER PARTY, PEANUT BUTTER ICE CREAM, PEANUT BUTTER AND FUDGE SWIRLS, PEANUT BUTTER CUPS, UPC: 070640012411",
"ndbno": "45110466",
"ds": "BL"
}
]
}
}
我用 https://jsonformatter.curiousconcept.com/ 检查了 JSON 响应,这很好。我希望你能告诉我原因,因为我对 Golang 还很陌生。
我的结构:
type List struct {
Q string `json:"q,omitempty"`
Sr string `json:"sr,omitempty"`
Ds string `json:"ds,omitempty"`
Start string `json:"start,omitempty"`
End string `json:"end,omitempty"`
Total string `json:"total,omitempty"`
Group string `json:"group,omitempty"`
Sort string `json:"sort,omitempty"`
Item []Item `json:"item,omitempty"`
}
type Item struct {
Offset string `json:"offset,omitempty"`
Group string `json:"group,omitempty"` //food group to which the food belongs
Name string `json:"name,omitempty"` //the food’s name
Ndbno string `json:"nbno,omitempty"` //the food’s NDB Number
Ds string `json:"ds,omitempty"` //Data source: BL=Branded Food Products or SR=Standard Release
}
代码:
func (sr *SearchRequest) fetch() {
url := "https://api.nal.usda.gov/ndb/search/?" +
"format=" + sr.format +
"&q=" + sr.q +
"&sort=" + sr.sort +
"&max=" + strconv.FormatInt(sr.max, 10) +
"&offset=" + strconv.FormatInt(sr.offset, 10) +
"&api_key=" + sr.c.ApiKey
r, err := http.Get(url)
if err != nil {
panic(err.Error())
}
defer r.Body.Close()
b, err := ioutil.ReadAll(r.Body)
if err != nil {
panic(err.Error())
}
l := new(List)
err = json.Unmarshal(b, &l)
if err != nil {
fmt.Println(err)
}
fmt.Println(l)
}
最佳答案
Go 类型与 JSON 的结构不匹配。 JSON 中还有一层对象。试试这个:
var v struct {
List List
}
err := json.Unmarshal([]byte(data), &v)
一些字符串字段对应于 JSON 中的数字。使用数字类型(int、float64、...)声明这些字段。
关于json - Golang 从 api.nal.usda.gov/ndb 解码 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43349648/
在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这
我有用于控制用户任务的Rails5API项目,我有以下错误,但并非总是针对相同的Controller和路由。ActionController::RoutingError:uninitializedconstantApi::V1::ApiController我向您描述了一些我的项目,以更详细地解释错误。应用结构路线scopemodule:'api'donamespace:v1do#=>Loginroutesscopemodule:'login'domatch'login',to:'sessions#login',as:'login',via::postend#=>Teamroutessc
我有一个非常简单的RubyRack服务器,例如:app=Proc.newdo|env|req=Rack::Request.new(env).paramspreq.inspect[200,{'Content-Type'=>'text/plain'},['Somebody']]endRack::Handler::Thin.run(app,:Port=>4001,:threaded=>true)每当我使用JSON对象向服务器发送POSTHTTP请求时:{"session":{"accountId":String,"callId":String,"from":Object,"headers":
在应用开发中,有时候我们需要获取系统的设备信息,用于数据上报和行为分析。那在鸿蒙系统中,我们应该怎么去获取设备的系统信息呢,比如说获取手机的系统版本号、手机的制造商、手机型号等数据。1、获取方式这里分为两种情况,一种是设备信息的获取,一种是系统信息的获取。1.1、获取设备信息获取设备信息,鸿蒙的SDK包为我们提供了DeviceInfo类,通过该类的一些静态方法,可以获取设备信息,DeviceInfo类的包路径为:ohos.system.DeviceInfo.具体的方法如下:ModifierandTypeMethodDescriptionstatic StringgetAbiList()Obt
我正在使用Mandrill的RubyAPIGem并使用以下简单的测试模板:testastic按照Heroku指南中的示例,我有以下Ruby代码:require'mandrill'm=Mandrill::API.newrendered=m.templates.render'test-template',[{:header=>'someheadertext',:main_section=>'Themaincontentblock',:footer=>'asdf'}]mail(:to=>"JaysonLane",:subject=>"TestEmail")do|format|format.h
我正在尝试使用Ruby2.0.0和Rails4.0.0提供的API从imgur中提取图像。我已尝试按照Ruby2.0.0文档中列出的各种方式构建http请求,但均无济于事。代码如下:require'net/http'require'net/https'defimgurheaders={"Authorization"=>"Client-ID"+my_client_id}path="/3/gallery/image/#{img_id}.json"uri=URI("https://api.imgur.com"+path)request,data=Net::HTTP::Get.new(path
我正在使用ruby2.1.0我有一个json文件。例如:test.json{"item":[{"apple":1},{"banana":2}]}用YAML.load加载这个文件安全吗?YAML.load(File.read('test.json'))我正在尝试加载一个json或yaml格式的文件。 最佳答案 YAML可以加载JSONYAML.load('{"something":"test","other":4}')=>{"something"=>"test","other"=>4}JSON将无法加载YAML。JSON.load("
Rails相对较新。我正在尝试调用一个API,它应该向我返回一个唯一的URL。我的应用程序中捆绑了HTTParty。我已经创建了一个UniqueNumberController,并且我已经阅读了几个HTTParty指南,直到我想要什么,但也许我只是有点迷路,真的不知道该怎么做。基本上,我需要做的就是调用API,获取它返回的URL,然后将该URL插入到用户的数据库中。谁能给我指出正确的方向或与我分享一些代码? 最佳答案 假设API为JSON格式并返回如下数据:{"url":"http://example.com/unique-url"
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我的公司有一个巨大的数据库,该数据库接收来自多个来源的(许多)事件,用于监控和报告目的。到目前为止,数据中的每个新仪表板或图形都是一个新的Rails应用程序,在巨大的数据库中有额外的表,并且可以完全访问数据库内容。最近,有一个想法让外部(不是我们公司,而是姊妹公司)客户访问我们的数据,并且决定我们应该公开一个只读的RESTfulAPI来查询我们的数据。我的观点是-我们是否也应该为我们的自己
我读了"BingSearchAPI-QuickStart"但我不知道如何在Ruby中发出这个http请求(Weary)如何在Ruby中翻译“Stream_context_create()”?这是什么意思?"BingSearchAPI-QuickStart"我想使用RubySDK,但我发现那些已被弃用前(Rbing)https://github.com/mikedemers/rbing您知道Bing搜索API的最新包装器(仅限Web的结果)吗? 最佳答案 好吧,经过一个小时的挫折,我想出了一个办法来做到这一点。这段代码很糟糕,因为它是