Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i declare list of maps in golang

Tags:

go

i am not getting how should i format the struct in golang so that i can get the list of maps (key/value pairs) in JSON format ? So far i tried with this

package main

import (
"encoding/json"
"fmt"
)

func main() {
map1 := map[string]interface{}{"dn": "abc", "status": "live", "version": 2, "xyz": 3}
map2, _ := json.Marshal(map1)
fmt.Println(string(map2))
}

here it is just printing key/value pairs...

{"dn":"abc","status":"live","version":2,"xyz":3}

but i need output something like this :

[{"dn":"abc","status":"live"},{"version":2,"xyz":3}]

like image 213
user2315104 Avatar asked Nov 06 '17 04:11

user2315104


People also ask

How do you declare a map in Go?

Go by Example: Maps Maps are Go's built-in associative data type (sometimes called hashes or dicts in other languages). To create an empty map, use the builtin make : make(map[key-type]val-type) . Set key/value pairs using typical name[key] = val syntax. Printing a map with e.g. fmt.

How do you initialize a map in Golang?

Initializing map using map literals: Map literal is the easiest way to initialize a map with data just simply separate the key-value pair with a colon and the last trailing colon is necessary if you do not use, then the compiler will give an error.

How do I get map values in Go?

You can retrieve the value assigned to a key in a map using the syntax m[key] . If the key exists in the map, you'll get the assigned value. Otherwise, you'll get the zero value of the map's value type.


1 Answers

As suggested by @Volker, you should use slice of maps:

package main

import (
    "fmt"
    "encoding/json"
)

// M is an alias for map[string]interface{}
type M map[string]interface{}

func main() {
    var myMapSlice []M

    m1 := M{"dn": "abc", "status": "live"}

    m2 := M{"version": 2, "xyz": 3}

    myMapSlice = append(myMapSlice, m1, m2)

    // or you could use `json.Marshal(myMapSlice)` if you want
    myJson, _ := json.MarshalIndent(myMapSlice, "", "    ")
    fmt.Println(string(myJson))
}

Outputs:

[
    {
        "dn": "abc",
        "status": "live"
    },
    {
        "version": 2,
        "xyz": 3
    }
]

From the code, I've used an alias for map[string]interface{} to make it more convenient to initialize a map of interface.

Link to code: https://play.golang.org/p/gu3xafnAyG

like image 158
stevenferrer Avatar answered Oct 09 '22 15:10

stevenferrer