snippetgoCritical
Convert Go map to json
Viewed 0 times
convertjsonmap
Problem
I tried to convert my Go map to a json string with
Here's my code :
My output is :
I really don't know where I'm wrong. Thank you for your help.
encoding/json Marshal, but it resulted in a empty string.Here's my code :
package main
import (
"encoding/json"
"fmt"
)
type Foo struct {
Number int `json:"number"`
Title string `json:"title"`
}
func main() {
datas := make(map[int]Foo)
for i := 0; i < 10; i++ {
datas[i] = Foo{Number: 1, Title: "test"}
}
jsonString, _ := json.Marshal(datas)
fmt.Println(datas)
fmt.Println(jsonString)
}My output is :
map[9:{1 test} 2:{1 test} 7:{1 test} 3:{1 test} 4:{1 test} 5:{1 test} 6:{1 test} 8:{1 test} 0:{1 test} 1:{1 test}]
[]I really don't know where I'm wrong. Thank you for your help.
Solution
If you had caught the error, you would have seen this:
The thing is you cannot use integers as keys in JSON; it is forbidden. Instead, you can convert these values to strings beforehand, for instance using
See this post for more details: https://stackoverflow.com/a/24284721/2679935
jsonString, err := json.Marshal(datas)
fmt.Println(err)
// [] json: unsupported type: map[int]main.FooThe thing is you cannot use integers as keys in JSON; it is forbidden. Instead, you can convert these values to strings beforehand, for instance using
strconv.Itoa.See this post for more details: https://stackoverflow.com/a/24284721/2679935
Code Snippets
jsonString, err := json.Marshal(datas)
fmt.Println(err)
// [] json: unsupported type: map[int]main.FooContext
Stack Overflow Q#24652775, score: 167
Revisions (0)
No revisions yet.