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

Time:03-24

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!

CodePudding user response:

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.

  • Related