我有一个较大的 (10mb) JSON 文件,我试图将其解码到 map 中,以便在需要时从内存中读取它。我的问题是我无法弄清楚如何通过 json 中每一行的 id 来键入 map ,即使这是解决问题的惯用方法。
它包含很多嵌套数据,但为了简单起见,它基本上是这样的:
[{"id": "086687173", "count": 5}, {"id": "078382574", "count": 3}]
type Item struct {
Id string `json:"id"`
Count int `json:"count"`
}
data := []Item // am able to marshal into an array
data := make(map[string]Item) // cannot unmarshal array into Go value of type map[string]Item
bytes, _ := ioutil.ReadFile("./templates/data.json")
err := json.Unmarshal(bytes, &data)
fmt.Println(data)
最佳答案
My problem is that I can't figure out how to key the map by the id
您无法为 map 编制索引,因为您没有任何 map 。
您的输入 JSON 是一个 JSON 数组,因此您可以将其解码为 Go slice 。之后你必须自己构建一个 Go map 。然后您可以通过 Id
索引该 map :
m := map[string]*Item{}
for i := range data {
m[data[i].Id] = &data[i]
}
fmt.Println(m)
fmt.Println(m["086687173"])
fmt.Println(m["078382574"])
这将输出(在 Go Playground 上尝试):
[{086687173 5} {078382574 3}] <nil>
map[078382574:0x43015c 086687173:0x430150]
&{086687173 5}
&{078382574 3}
请注意,如果您最初会使用指针 slice []*Item
,则创建 map 会更简单:
m := map[string]*Item{}
for _, item := range data {
m[item.Id] = item
}
输出是一样的。在 Go Playground 上试试这个.
关于arrays - 将 json 文件编码到 map 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56756534/