如果我的問題措辭不當,我深表歉意。我是 Go 的新手,正在嘗試使用封送處理將一些數據格式化為 JSON。我的功能看起來像:func writeJSON(w http.ResponseWriter, rep similarity.Similarity, keys []string) { for _, sub := range rep.Submissions { var jsonMap = make(map[string]interface{}) vals := makeRow(sub) for i := range vals { jsonMap[keys[i]] = vals[i] } jsonData, err := json.Marshal(jsonMap) if err != nil { zap.L().Error(err.Error()) } w.Write(jsonData) }}我基本上是通過為每個提交(sub-rep.Submission)創建一個映射,添加我想要的鍵和值,并在完成后進行編組來獲得鍵:值結構。但是,我得到的是單獨的 json 對象,而不是單個對象。我當前的 json 響應格式如下所示:{ "correct": "false", "learnerId": "student_03", "percentScore": "0.000000", "solutionCode": "x = 4", "solutionId": "515219a8", "submittedTime": "03/23/2022 05:58 PM UTC", "testsPassed": "0", "totalTests": "1"}{ "correct": "false", "learnerId": "student_02", "percentScore": "0.000000", "solutionCode": "x = \"hello\";", "solutionId": "c5fe8f93", "submittedTime": "03/23/2022 05:57 PM UTC", "testsPassed": "0", "totalTests": "1"}{ "correct": "true", "learnerId": "student_01", "percentScore": "0.000000", "solutionCode": "x = 2;", "solutionId": "c2be6a1f", "submittedTime": "03/23/2022 05:43 PM UTC", "testsPassed": "1", "totalTests": "1"}我想要這樣的東西:{ { "correct": "false", "learnerId": "student_03", "percentScore": "0.000000", "solutionCode": "x = 4", "solutionId": "asdad", "submittedTime": "03/23/2022 05:58 PM UTC", "testsPassed": "0", "totalTests": "1" },}我試過將 jsonData, err := json.Marshal(jsonMap) 部分從 for 循環中取出,但這不起作用。我也嘗試過使用 json.NewEncoder(w).Encode(jsonMap) 但這會產生與封送處理類似的結果。關于我可以嘗試什么的任何想法?謝謝!
2 回答

繁華開滿天機
TA貢獻1816條經驗 獲得超4個贊
使用以下代碼將地圖編組為 JSON 數組:
func writeJSON(w http.ResponseWriter, rep similarity.Similarity, keys []string) {
var result []interface{}
for _, sub := range rep.Submissions {
var jsonMap = make(map[string]interface{})
vals := makeRow(sub)
for i := range vals {
jsonMap[keys[i]] = vals[i]
}
result = append(result, jsonMap)
}
json.NewEncoder(w).Encode(result)
}
此代碼不會產生您預期的結果,但它可能是您想要的。預期結果不是有效的 JSON。
- 2 回答
- 0 關注
- 103 瀏覽
添加回答
舉報
0/150
提交
取消