如果我的问题措辞不当,我深表歉意。我是 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 关注
- 79 浏览
添加回答
举报
0/150
提交
取消