Answer the question
In order to leave comments, you need to log in
How to correctly parse JSON (Golang)?
There is a JSON like this:
data := []byte(`{
"ID":134,
"Number":"ИЛМ-1274",
"Year":2,
"Students":[
{
"LastName":"Вещий",
"FirstName":"Лифон",
"MiddleName":"Вениаминович",
"Birthday":"4апреля1970года",
"Address":"632432,г.Тобольск,ул.Киевская,дом6,квартира23",
"Phone":"+7(948)709-47-24",
"Rating":[1,2,3]
}
]}`)
package main
import (
"encoding/json"
"fmt"
)
type Students struct {
Rating []int
}
type myStruct struct {
Students []Students
}
func main() {
var m myStruct
if err := json.Unmarshal(temp_json, &m); err != nil {
fmt.Println(err)
return
}
}
Answer the question
In order to leave comments, you need to log in
Your m is a structure that has an element with the key Students. It needs to be iterated over
package main
import (
"encoding/json"
"fmt"
)
type Students struct {
Rating []int
}
type myStruct struct {
Students []Students
}
func main() {
data := []byte(`{
"ID":134,
"Number":"ИЛМ-1274",
"Year":2,
"Students":[
{
"LastName":"Вещий",
"FirstName":"Лифон",
"MiddleName":"Вениаминович",
"Birthday":"4апреля1970года",
"Address":"632432,г.Тобольск,ул.Киевская,дом6,квартира23",
"Phone":"+7(948)709-47-24",
"Rating":[1,2,3]
}
]}`)
var m myStruct
if err := json.Unmarshal(data, &m); err != nil {
fmt.Println(err)
return
}
fmt.Println(m.Students)
for _, student := range m.Students {
fmt.Println(student.Rating)
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question