Dinesh Sonachalam
Dinesh Sonachalam

Reputation: 1369

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.

Upvotes: 2

Views: 6018

Answers (2)

saddam
saddam

Reputation: 829

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

Upvotes: 9

Schidu Luca
Schidu Luca

Reputation: 3947

For me this more looks like an array of objects. You can have your desired output like this:

type data struct {
    Id string
    Name string
}

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

    for counter := range id {
        parsedData = append(parsedData, data{Name: name[counter], Id: id[counter]})
    }

    bytes, _ := json.Marshal(parsedData)
    fmt.Print(string(bytes))
}

The output should look like this:

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

Upvotes: 4

Related Questions