英文:
Golang access nested element on Json
问题
我有以下的golang代码,试图访问数组元素,我的期望是打印"bxar",但是它抛出了错误,有什么想法吗?
package main
import (
"encoding/json"
"fmt"
)
type Data struct {
Args struct {
Foo string
}
}
func main() {
in := `[{"args": {"foo": "bar"}},{"args": {"foo": "bxar"}}]`
var d []Data
json.Unmarshal([]byte(in), &d)
fmt.Println("Foo:", d[1].Args.Foo)
//fmt.Printf("Result: %+v", d)
}
英文:
I have the following golang code which trying to access elements on array my expectation to print bxar ,but it throw error any idea?
package main
import (
"encoding/json"
"fmt"
)
type Data struct {
Args struct {
Foo string
}
}
func main() {
in := `[{"args": {"foo": "bar"}},{"args": {"foo": "bxar"}}]}`
var d []Data
json.Unmarshal([]byte(in), &d)
fmt.Println("Foo:", d[1].Args.Foo)
//fmt.Printf("Result: %+v", d)
}
答案1
得分: 5
这个不起作用的原因是一个拼写错误。在你的 JSON 中有一个多余的 }
:
之前的代码:
`[{"args": {"foo": "bar"}},{"args": {"foo": "bxar"}}]}`
之后的代码:
`[{"args": {"foo": "bar"}},{"args": {"foo": "bxar"}}]`
请参考这个 playground:https://go.dev/play/p/sL8Cx8lF6WR
英文:
The reason it does not work is a typo. There is one too many }
in your JSON:
Before:
`[{"args": {"foo": "bar"}},{"args": {"foo": "bxar"}}]}`
After:
`[{"args": {"foo": "bar"}},{"args": {"foo": "bxar"}}]`
See this playground: https://go.dev/play/p/sL8Cx8lF6WR
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论