Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create JSON array of objects using Go map?

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.

like image 227
Dinesh Sonachalam Avatar asked Jun 07 '26 12:06

Dinesh Sonachalam


1 Answers

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"}]
like image 73
saddam Avatar answered Jun 10 '26 04:06

saddam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!