<p>Hey <a href="/r/golang" rel="nofollow">/r/golang</a>!</p>
<p>I've been working on teaching myself Golang off and on for a few months, and so far it's been going great. I've run into a bit of a brick wall with handling the json response from a REST api, and I think it's because there's a concept that I've just not getting. I'd appreciate a second set of eyes if anyone can spare them. </p>
<p>Here's my struct and function to fetch JSON from a remote API and marshal it into a json structure (generated using jsonutil):</p>
<pre><code>type Tests []struct {
ID int64 `json:"id"`
CreatedAt string `json:"created_at"`
Status string `json:"status"`
Type string `json:"type"`
}
func tests() (){
url := *serverURL + "/tests"
client := &http.Client{}
req, err := http.NewRequest("GET", url, nil)
res, err := client.Do(req)
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
var jData Tests
err = json.Unmarshal([]byte(body), &jData)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
for i := range jData {
fmt.Println(jData[i])
}
}
</code></pre>
<p>A raw curl request to the REST endpoint returns this:</p>
<pre><code>curl "http://localhost/v1/tests"
[{"id":1254,"type":"final","status":"submitted","created_at":"2015-04-27 02:22:41"},
{"id":9999,"type":"midterm","status":"submitted","created_at":"2015-04-27 02:22:48"}
</code></pre>
<p>When my go code is compiled and executed, the fmt.Println statement prints out, line by line, the two entries returned by the REST API:</p>
<pre><code> {1254 2015-04-27 02:22:41 submitted final}
{9999 2015-04-27 02:22:41 submitted midterm}
</code></pre>
<p>...but I actually want to be able to access, decorate and print out the fields in those json entries, so that my output looks more like:</p>
<pre><code>1254 Submitted Final Exam on April 27, 2014
9999 Submitted Midterm Exam on April 27, 2014
</code></pre>
<p>I'm not sure whether I need to write a json decoder, or change the struct my json is marshaled into, or where exactly to go from here. Any advice on how to proceed?</p>
<hr/>**评论:**<br/><br/>dfuentes: <pre><p>You'll want to access each field individually of the struct and format it using something like Printf. So for your example, it would look something like:</p>
<pre><code>for _, data := range jData {
fmt.Printf("%s %s %s Exam on %s\n", data.ID, data.Status, data.Type, data.CreatedAt)
}
</code></pre></pre>Blackmirth: <pre><p>Just to expand on this point for clarification:
The format that is being printed, i.e.</p>
<pre><code>{1254 2015-04-27 02:22:41 submitted final}
{9999 2015-04-27 02:22:41 submitted midterm}
</code></pre>
<p>is just the standard format that fmt uses when asked to print a struct. The data has successfully unmarshalled into the struct properly - it is just that the key:value pairs are not included when you print it.</p></pre>blueblank: <pre><pre><code>fmt.Printf("%+v\n", data)
</code></pre>
<p>would output key:value pairs</p></pre>golangthrowaway: <pre><p>Whoops. I suppose this should say I have my json Unmarshalled in the topic. Sorry for the confusion.</p></pre>singron: <pre><p>Unrelated to your question, but you only check <code>err</code> after unmarshalling. If any of the previous operations failed, you wouldn't know why (and in some cases, you might not notice at all).</p></pre>jayposs: <pre><p>Hope this helps. </p>
<pre><code>type Test struct {
ID int64 `json:"id"`
CreatedAt string `json:"created_at"`
Status string `json:"status"`
Type string `json:"type"`
}
var tests []Test
json.NewDecoder(res.Body).Decode(tests)
for _, test := range tests {
fmt.Printf("%s, %s, %s", test.CreatedAt, test.Status, test.Type);
</code></pre>
<p>}</p></pre>jasonrichardsmith: <pre><p>Your type is a slice. Of a defined structure so when you are looping over it "i" is just the index of the slice not the actual values, essentially you are dumping the the individual structures in the slice into Println. You need to delve down another level and access each field.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传