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}]
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With