英文:
Why am I not able to decode this JSON with golang? It always prints an empty string
问题
我在我的服务器上有一个非常简单的JSON文件,内容如下:
{
"first_name": "John",
"last_name": "Doe"
}
然后我编写了一个用于打印出名字的Golang脚本:
package main
import (
"fmt"
"net/http"
"encoding/json"
)
type Person struct {
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
}
func main() {
url := "http://myserver.com/test.json"
res, err := http.Get(url)
if err != nil {
fmt.Printf("%s", err)
}
defer res.Body.Close()
var person Person
dec := json.NewDecoder(res.Body).Decode(&person)
if dec != nil {
fmt.Printf("%s", dec)
}
fmt.Println(person.FirstName)
}
但是,当我运行go run test.go
时,它总是只打印一个换行符。我做错了什么?
英文:
I have a JSON file on my server that is very simple, just
{
"first_name": "John",
"last_name": "Doe"
}
I then wrote a golang script to print out the first name:
package main
import (
"fmt"
"net/http"
"encoding/json"
)
type Person struct {
FirstName string `json: "first_name"`
LastName string `json: "last_name"`
}
func main() {
url := "http://myserver.com/test.json"
res, err := http.Get(url)
if err != nil {
fmt.Printf("%s", err)
}
defer res.Body.Close()
var person Person
dec := json.NewDecoder(res.Body).Decode(&person)
if dec != nil {
fmt.Printf("%s", dec)
}
fmt.Println(person.FirstName)
}
But if I type go run test.go
it always just prints a newline character seemingly.
What am I doing wrong?
答案1
得分: 2
你的代码正在搜索json中的FirstName
和LastName
键。如果你想让结构标签生效,你需要在冒号和引号之间去掉空格,即json:"first_name"
。
你可以参考这个链接了解更多关于结构标签的信息:https://golang.org/pkg/reflect/#StructTag
英文:
Your code is searching FirstName
and LastName
keys in your json. If you want struct tags take effect, you need to remove space between colon and quote. json:"first_name"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论