開(kāi)滿天機(jī)
2022-11-23 19:56:19
如果我的問(wèn)題措辭不當(dāng),我深表歉意。我是 Go 的新手,正在嘗試使用封送處理將一些數(shù)據(jù)格式化為 JSON。我的功能看起來(lái)像: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) }}我基本上是通過(guò)為每個(gè)提交(sub-rep.Submission)創(chuàng)建一個(gè)映射,添加我想要的鍵和值,并在完成后進(jìn)行編組來(lái)獲得鍵:值結(jié)構(gòu)。但是,我得到的是單獨(dú)的 json 對(duì)象,而不是單個(gè)對(duì)象。我當(dāng)前的 json 響應(yīng)格式如下所示:{ "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" },}我試過(guò)將 jsonData, err := json.Marshal(jsonMap) 部分從 for 循環(huán)中取出,但這不起作用。我也嘗試過(guò)使用 json.NewEncoder(w).Encode(jsonMap) 但這會(huì)產(chǎn)生與封送處理類似的結(jié)果。關(guān)于我可以嘗試什么的任何想法?謝謝!
2 回答

繁華開(kāi)滿天機(jī)
TA貢獻(xiàn)1816條經(jīng)驗(yàn) 獲得超4個(gè)贊
使用以下代碼將地圖編組為 JSON 數(shù)組:
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)
}
此代碼不會(huì)產(chǎn)生您預(yù)期的結(jié)果,但它可能是您想要的。預(yù)期結(jié)果不是有效的 JSON。
- 2 回答
- 0 關(guān)注
- 106 瀏覽
添加回答
舉報(bào)
0/150
提交
取消