D
D
Dmitry2020-08-10 21:17:06
go
Dmitry, 2020-08-10 21:17:06

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]
        }	
  ]}`)


It is required to calculate the sum of elements of the Rating array for each student.
I'm trying to do it this way, but I don't understand how to access the Rating elements?

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
  }
}


Here m is a structure, I can't iterate over it.
Tell me how to fix it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pavel Virsky, 2020-08-10
@dima2308

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 question

Ask a Question

731 491 924 answers to any question