Answer the question
In order to leave comments, you need to log in
How to output json in golang not as objects, but as an array?
I am getting response from json server in the form of objects in an object, but I want to receive it in the form of objects in an array.
This is the response I get
{"70":{"Id":70,"Exam_Id":5,"Student_Id":2,"Student_Fio":"Иванов"},"71":{"Id":71,"Exam_Id":5,"Student_Id":3,"Student_Fio":"Петров"}
[{"Id":70,"Exam_Id":5,"Student_Id":2,"Student_Fio":"Иванов"},{"Id":71,"Exam_Id":5,"Student_Id":3,"Student_Fio":"Петров"}]
type StudentsExam struct{
Id int
Exam_Id int
Student_Id int
Student_Fio string
}
func getData(Exam_Id int) {
mapToEncode := make(map[string] StudentsExam)
for id, stud_exam := range StudentsExamList {
if stud_exam.Exam_Id == Exam_Id {
mapToEncode[strconv.Itoa(id)] = stud_exam
}
}
data, err := json.Marshal(mapToEncode)
if err != nil {
log.Println("error: %v\n", err)
return
}
}
Answer the question
In order to leave comments, you need to log in
Preved))
Why are you using a display where you want to use a slice?))
StudentsExamList - here you are lying in the name, and brazenly, this display with string keys (id) is not clear why this is so, it's just storing the data that you need in another form.
type StudentExam struct{
ID int
ExamID int
StudentID int
StudentFIO string
}
func findStudentsByExamID(id uint) []*StudentExam {
result := make([]*StudentsExam, len(StudentsExamList))
var i uint
for _, studentExam := range StudentsExamList {
if studentExam.ID == id {
result[i] = studentExam
}
i++
}
return result
}
func DataToJSON(data interface{}) []byte {
result, err := json.Marshal(data)
if err == nil {
return result
}
log.Printf("error: %v\n", err)
return []byte{}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question