I have search for a solution for this problem. It is actually from a sql database, but this illustrates the problem as well:
package main
import (
"fmt"
"encoding/json"
)
func main() {
m := map[string]string{
"USER_ID":"JD",
"USER_NAME":"John Doe",
}
json, _ := json.Marshal(m)
for i := 0; i < 4; i++ {
fmt.Println(string(json))
}
}
https://play.golang.org/p/7DQPiB0aWAK
Each row is correct, but it each row is not separated by comma and surrounded by square brackets.
{"USER_ID":"JD","USER_NAME":"John Doe"}
{"USER_ID":"JD","USER_NAME":"John Doe"}
{"USER_ID":"JD","USER_NAME":"John Doe"}
{"USER_ID":"JD","USER_NAME":"John Doe"}
The desired output is this:
[{"USER_ID":"JD","USER_NAME":"John Doe"},
{"USER_ID":"JD","USER_NAME":"John Doe"},
{"USER_ID":"JD","USER_NAME":"John Doe"},
{"USER_ID":"JD","USER_NAME":"John Doe"}]
Is this possible using map[string]string or interface?
Is this possible using map[string]string or interface?
The answer is simple - You can use a slice whenever you want to produce a list output in JSON.
Here is your example with the desired output (playground) :
package main
import (
"fmt"
"encoding/json"
)
func main() {
// define a slice of maps
var mySlice []map[string]string
// define a map
m := map[string]string{
"USER_ID":"JD",
"USER_NAME":"John Doe",
}
// add the map 4 times to the slice
for i := 0; i < 4; i++ {
mySlice = append(mySlice, m)
}
// print the slice
json, _ := json.Marshal(mySlice)
fmt.Println(string(json))
}
// Output: [{"USER_ID":"JD","USER_NAME":"John Doe"},{"USER_ID":"JD","USER_NAME":"John Doe"},{"USER_ID":"JD","USER_NAME":"John Doe"},{"USER_ID":"JD","USER_NAME":"John Doe"}]