英文:
Using Golang json.NewDecoder / json.NewEncoder
问题
我是你的中文翻译助手,以下是翻译好的内容:
我是一个完全不懂Go语言的新手,我正在尝试理解我在这里缺少了什么。我期望使用dec.Decode
循环遍历JSON值,并最终得到一个响应的映射。但我得到的是整个JSON字符串作为映射的第一个元素的键。我错过了什么?
示例响应:
2015/03/02 10:03:16 map[error:invalid_request error_description:that is not a recognized WePay API call error_code:1001] map[string]interface {}
package main
import (
"encoding/json"
"io"
"log"
"net/http"
"reflect"
)
func main() {
var v map[string]interface{}
resp, err := http.Get("https://wepayapi.com/v2/")
if err != nil {
log.Println("Error: " + err.Error())
}
defer resp.Body.Close()
// resp.Body is an io.ReadCloser... NewDecoder expects an io.Reader
dec := json.NewDecoder(resp.Body)
// Decode reads the next JSON-encoded value from its input and stores it in the value pointed to by v.
for err := dec.Decode(&v); err != nil && err != io.EOF; {
log.Println("ERROR: " + err.Error())
return
}
log.Println(v, reflect.TypeOf(v))
}
英文:
I'm a total noob at go and I'm trying to understand what I'm missing here. I'm expecting to use dec.Decode
to loop over the json values and end up with a map of the response. What I'm getting is the entire json string as the key to the first element of the map. What am I missing?
Example response:
2015/03/02 10:03:16 map[error:invalid_request error_description:that is not a recognized WePay API call error_code:1001] map[string]interface {}
package main
import (
"encoding/json"
"io"
"log"
"net/http"
"reflect"
)
func main() {
var v map[string]interface{}
resp, err := http.Get("https://wepayapi.com/v2/")
if err != nil {
log.Println("Error: " + err.Error())
}
defer resp.Body.Close()
// resp.Body is an io.ReadCloser... NewDecoder expects an io.Reader
dec := json.NewDecoder(resp.Body)
// Decode reads the next JSON-encoded value from its input and stores it in the value pointed to by v.
for err := dec.Decode(&v); err != nil && err != io.EOF; {
log.Println("ERROR: " + err.Error())
return
}
log.Println(v, reflect.TypeOf(v))
}
答案1
得分: 2
Decoder
会一次性解码整个JSON
值(在这种情况下是错误对象),你不需要在循环中调用它:
if err := dec.Decode(&v); err != nil {
log.Println("ERROR: " + err.Error())
return
}
作为响应,你会得到一个等价于这个JSON
的映射:
{
"error": "invalid_request",
"error_description": "that is not a recognized WePay API call",
"error_code": 1001
}
结果:
map[string]interface{} {
"error": "invalid_request",
"error_description": "that is not a recognized WePay API call",
"error_code": 1001,
}
英文:
Decoder
will decode the whole JSON
value at once (in this case the error object), you don;y have to call it in a loop:
if err := dec.Decode(&v); err != nil {
log.Println("ERROR: " + err.Error())
return
}
As a response you get a map equavalent of this JSON
:
{"error":"invalid_request","error_description":"that is not a recognized WePay API call","error_code":1001}
Result:
map[string]interface{} {
"error":"invalid_request",
"error_description":"that is not a recognized WePay API call",
"error_code":1001,
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论