How to create JSON array of objects using Go map?

Issue

I need to create a JSON array using map.

package main
import "fmt"
func main(){
    id := [5]string{"1","2","3","4","5"}
    name := [5]string{"A","B","C","D","E"}
    parseData := make(map[string]string)
    for counter,_ := range id {
        parseData["id"] = id[counter]
        parseData["name"] = name[counter]
        fmt.Println(parseData)
    }

}

My current output:

map[id:1 name:A]
map[id:2 name:B]
map[id:3 name:C]
map[id:4 name:D]
map[id:5 name:E]

I need a JSON output like below:

[{id:1, name:A},
{id:2, name:B},
{id:3, name:C},
{id:4, name:D},
{id:5, name:E}]

I know basics of using map its a dictionary used for key:value pairs.How can I achieve JSON output using map.

Solution

To create array of JSON through map, you need to create one map as a slice and another one just single map and then assign value one by one in single map then append this into slice of map, like follow the below code:

package main

import (
    "fmt"
    "encoding/json"
)

func main(){
    id := [5]string{"1","2","3","4","5"}
    name := [5]string{"A","B","C","D","E"}

    parseData := make([]map[string]interface{}, 0, 0)

    for counter,_ := range id {
        var singleMap = make(map[string]interface{})
        singleMap["id"] = id[counter]
        singleMap["name"] = name[counter]
        parseData = append(parseData, singleMap)
    }
    b, _:= json.Marshal(parseData)
    fmt.Println(string(b))
}

Also you can test over here

it prints JSON as:

[{"id":"1","name":"A"},
{"id":"2","name":"B"},
{"id":"3","name":"C"},
{"id":"4","name":"D"},
{"id":"5","name":"E"}]

Answered By – saddam

Answer Checked By – Candace Johnson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.