如果我的问题措辞不当,我深表歉意。我是 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"
},
{
"correct": "false",
"learnerId": "student_02",
"percentScore": "0.000000",
"solutionCode": "x = \"hello\";",
"solutionId": "asdasd",
"submittedTime": "03/23/2022 05:57 PM UTC",
"testsPassed": "0",
"totalTests": "1"
},
{
"correct": "true",
"learnerId": "student_01",
"percentScore": "0.000000",
"solutionCode": "x = 2;",
"solutionId": "asd",
"submittedTime": "03/23/2022 05:43 PM UTC",
"testsPassed": "1",
"totalTests": "1"
}
}
我尝试将 jsonData, err := json.Marshal(jsonMap) 部分从 for 循环中取出,但这不起作用。我也尝试过使用 json.NewEncoder(w).Encode(jsonMap) 但这会产生与封送处理类似的结果。关于我可以尝试什么的任何想法?谢谢!
使用以下代码将映射编组为 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。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句