【问题标题】:Marshal json file into map将 json 文件编入地图
【发布时间】:2019-11-07 10:32:11
【问题描述】:

我有一个较大的 (10mb) JSON 文件,我正在尝试将其解组到地图中,以便在需要时从内存中读取它。我的问题是我无法弄清楚如何通过 json 中每一行的 id 来键入地图,或者即使这是解决问题的惯用方法。

它包含很多嵌套数据,但为了简单起见,它基本上是这样的:

[{"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)

【问题讨论】:

    标签: arrays json dictionary go slice


    【解决方案1】:

    我的问题是我不知道如何通过 id 键入地图

    您无法索引地图,因为您没有任何地图。

    您的输入 JSON 是一个 JSON 数组,因此您可以将其解组为 Go 切片。之后,您必须自己构建 Go 地图。然后您可以通过Id 索引该地图:

    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}
    

    请注意,如果您最初使用指针切片 []*Item,则创建映射会更简单:

    m := map[string]*Item{}
    for _, item := range data {
        m[item.Id] = item
    }
    

    输出是一样的。在Go Playground 上试试这个。

    【讨论】:

    • 谢谢,我想我只是希望能够在没有中间数组步骤的情况下直接编组到地图
    猜你喜欢
    • 1970-01-01
    • 2019-03-01
    • 1970-01-01
    • 2020-12-15
    • 2018-07-14
    • 1970-01-01
    • 1970-01-01
    • 2019-01-19
    • 1970-01-01
    相关资源
    最近更新 更多