arrays - 将 json 文件编码到 map 中

标签 arrays json dictionary go slice

我有一个较大的 (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/

相关文章:

javascript - 计算javascript对象数组中重复项的平均值

c - 将数组的一系列位置归零的最快方法?

javascript - Angularjs 将数组映射到另一个数组

c# - 如果其中一个 Json 键包含一个点,如何为 Json 序列化声明匿名类型?

java - 将 Map<String, Object> 转换为 Map<String, List<Object>>

javascript - 来自 queryselectorall 和 addeventlistener 问题的数组

javascript - 如何在 JavaScript 中使用根节点遍历 json

ios - 如何在 swift 3 中使用 HTTP Post 方法获取 JSON 数据?

c# - 字典 ContainsKey 方法

.net - 在 vb.net 4.0 中对字典的整数值字段求和