如果我的問題措辭不當,我深表歉意。我是 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) 但這會產生與封送處理類似的結果。關于我可以嘗試什么的任何想法?謝謝!
uj5u.com熱心網友回復:
使用以下代碼將映射編組為 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。
uj5u.com熱心網友回復:
您想要的格式無效,不是
{ {},{},}
應該:
[ {},{},]
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/448501.html
