英文:
Unable to iterate through the parsed JSON in google go
问题
我是新手学习Go编程,我试图解析以下格式的JSON
文件:
{
"movies": [
{
"name": "Inception",
"rating": 8.8,
"genres": [
"Action",
"Adventure",
"Sci-Fi"
]
},
{
"name": "Godfather",
"rating": 9.2,
"genres": [
"Crime",
"Drama"
]
}
]
}
使用以下代码:
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
)
type Movie struct {
name string
rating float64
genres []string
}
type MovieRating struct {
movies []Movie
genre map[string]float64
}
func (mr *MovieRating) init(filename string) {
var raw interface{}
data, _ := ioutil.ReadFile(filename)
_ = json.Unmarshal(data, &raw)
tmp := raw.(map[string]interface{})["movies"]
fmt.Println(tmp)
// 现在我需要在这里创建一个电影数组并赋值给mr.movies
}
func (mr *MovieRating) calculate_rating() {
fmt.Println("calculating")
}
func main() {
var mr MovieRating
mr.init("data.json")
mr.calculate_rating()
}
但是在解析后,我不知道如何遍历解析后的对象。解析后的对象是接口类型,我该如何遍历这个电影数组?
英文:
I am new to go programming, I was trying to parse a JSON
file of the following format:
{
"movies": [
{
"name": "Inception",
"rating": 8.8,
"genres": [
"Action",
"Adventure",
"Sci-Fi"
]
},
{
"name": "Godfather",
"rating": 9.2,
"genres": [
"Crime",
"Drama"
]
}
]
}
Using this code :
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
)
type Movie struct {
name string
rating float64
genres []string
}
type MovieRating struct {
movies []Movie
genre map[string]float64
}
func (mr *MovieRating) init(filename string) {
var raw interface{}
data, _ := ioutil.ReadFile(filename)
_ = json.Unmarshal(data, &raw)
tmp := raw.(map[string]interface{})["movies"]
fmt.Println(tmp)
// now I need to create an array of movies here and assign to mr.movies
}
func (mr *MovieRating) calculate_rating() {
fmt.Println("calculating")
}
func main() {
var mr MovieRating
mr.init("data.json")
mr.calculate_rating()
}
But after parsing I have no idea how to iterate through the parsed object. The parsed object is of interface type, How do I parse through this array of movies ?
答案1
得分: 6
对于你提供的内容,我已经为你翻译好了。以下是翻译的结果:
对于你的Json
文件,使用指向电影切片[]Movie
的指针进行解组,不要使用interface{}
。
还有一件事:
> json
包只能访问结构类型的公开字段(以大写字母开头的字段)。
**编辑:**这是一个解组电影数组的示例。
英文:
Unmarshal your Json
file against a pointer to slice of movies []Movie
, don't use interface{}
for that.
One more thing :
> The json package only accesses the exported fields of struct types
> (those that begin with an uppercase letter).
Edit: this is a working example of unmarshaling an array of movies.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论