Reputation: 2728
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}]
Upvotes: 17
Views: 27900
Reputation: 682
I had the same question, and answered myself (No struct
usage for my case)
package main
import "fmt"
func main() {
mapSlice := []map[string]interface{}{}
map1 := map[string]interface{}{"foo": "bar"}
mapSlice = append(mapSlice, map1)
fmt.Println(mapSlice[0]["foo"]) // prints "bar"
}
https://go.dev/play/p/BOCVAOngul2
Upvotes: 3
Reputation: 2612
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
Upvotes: 34