Reputation: 361
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 ?
Upvotes: 2
Views: 1001
Reputation: 26415
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.
Upvotes: 6