Creating a single json object with several nested objects from a map in Go

huangapple go评论66阅读模式
英文:

Creating a single json object with several nested objects from a map in Go

问题

抱歉,如果我的问题表达不清楚。我刚开始学习Go语言,尝试使用marshaling将一些数据格式化为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)创建一个映射,添加我想要的键和值,然后进行marshaling来获取键值对结构。然而,我得到的是单独的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),但结果与marshaling类似。你有什么想法我可以尝试的吗?谢谢!

英文:

Apologies if my question was worded poorly. I'm new to Go and trying to format some data into JSON by using marshaling. My function looks like:

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)
    }
}

I'm basically getting the key:value structure by creating a map for each submission (sub - rep.Submission), adding the key and value I want, and marshaling once thats done. However, I'm getting separate json objects instead of a single one.

My current json response format looks as follows:

{
    "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"
}

I would like something like this instead:

{
    {
        "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"
    }
}

I've tried taking the jsonData, err := json.Marshal(jsonMap) portion out of the for loops but that isn't working. I've also tried using json.NewEncoder(w).Encode(jsonMap) but that produces a similar result to marshaling. Any ideas on what I could try? Thank you!

答案1

得分: 0

使用以下代码将地图转换为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格式。

英文:

Use the following code to marshal the maps to a JSON array:

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)
}

This code does not produce your expected result, but it's probably what you want. The expected result is not valid JSON.

答案2

得分: 0

你想要的格式是无效的,不是

> { {}, {}, }

应该是:

> [
> {},
> {}, ]

英文:

the format your want is invalid,not

> { {}, {}, }

should be:

> [
> {},
> {}, ]

huangapple
  • 本文由 发表于 2022年3月24日 05:18:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/71594170.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定