Marshalを使用して Go マップを JSON 文字列に変換しようとしましたencoding/json
が、結果は空の文字列になりました。
これが私のコードです:
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)
}
私の出力は次のとおりです:
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}]
[]
どこが間違っているのか本当にわかりません。 ご協力ありがとうございます。
ベストアンサー1
エラーに気付いた場合は、次のように表示されます。
jsonString, err := json.Marshal(datas)
fmt.Println(err)
// [] json: unsupported type: map[int]main.Foo
JSON では整数をキーとして使用することはできません。これは禁止されています。代わりに、たとえば を使用して、これらの値を事前に文字列に変換することができますstrconv.Itoa
。
詳細については、この投稿をご覧ください。https://stackoverflow.com/a/24284721/2679935