R
R
Roman Rakzin2015-07-25 21:48:25
go
Roman Rakzin, 2015-07-25 21:48:25

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":"Петров"}

And I want to get one
[{"Id":70,"Exam_Id":5,"Student_Id":2,"Student_Fio":"Иванов"},{"Id":71,"Exam_Id":5,"Student_Id":3,"Student_Fio":"Петров"}]

Here's the code I wrote that doesn't output the data I want
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
    	    }
    }

data should be output as an array, not objects. Tell me how to do it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
index0h, 2015-07-25
@TwoRS

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

Some comments:
Separate logic. Output is one thing, data retrieval is another, a method that does both is not a good idea.
StudentsExamList as far as I understand is a global variable, they can only be used in exceptional situations. A global public variable is generally evil.
Don't create "getData" methods, specify for example: getStudentsByExamID(id uint) []*Student
"get**" methods assume that the data is guaranteed to be there, otherwise you should use the "find" prefix. In your case, what happens if examID = -157
Exam_Id, stud_exam go to the bright side, don't violate the codestyle.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question