json - 将 []struct 与 Json 一起使用

标签 json struct go

我正在尝试将 JSON 解析为 [] 结构,JSON 是从 https://api.github.com/events 检索到的 但是,当我尝试访问数组中的每个结构时,出现错误:

type GITHUB_EVENT does not support indexing

如何访问数组中的每个结构?

func httpGetEvents() {
    eventDataRAW := httpPageGet("https://api.github.com/events", true)
    eventDataJSON := new(GITHUB_EVENT)

    _ = json.Unmarshal([]byte(eventDataRAW), &eventDataJSON)

    fmt.Println(eventDataJSON[0].Id)
}

//--------------------------------------------------------------------------------------//

type GITHUB_EVENT []struct {
    Id    string `json:"id"`
    Type  string `json:"type"`
    Actor struct {
        Id         int    `json:"id"`
        Login      string `json:"login"`
        GravatarId string `json:"gravatar_id"`
        Url        string `json:"url"`
        AvatarUrl  string `json:"avatar_url"`
    } `json:"actor"`
    Repo struct {
        Id   int    `json:"id"`
        Name string `json:"name"`
        Url  string `json:"url"`
    } `json:"repo"`
    Payload struct {
        PushId       int    `json:"push_id"`
        Size         int    `json:"size"`
        DistinctSize int    `json:"distinct_size"`
        Ref          string `json:"ref"`
        Head         string `json:"head"`
        Before       string `json:"before"`
        Commits      []struct {
            Sha    string `json:"sha"`
            Author struct {
                Email string `json:"email"`
                Name  string `json:"name"`
            } `json:"author"`
            Message  string `json:"message"`
            Distinct bool   `json:"distinct"`
            Url      string `json:"url"`
        } `json:"commits"`
    } `json:"payload"`
    Public    bool   `json:"public"`
    CreatedAt string `json:"created_at"`
}

最佳答案

这个声明:

eventDataJSON := new(GITHUB_EVENT)

eventDataJSON 声明为 *GITHUB_EVENT(指向 slice 的指针),并将其初始化为 nil 指针。解码后,您可以通过在索引之前显式取消引用指针来访问第一个事件:

(*eventDataJSON)[0].Id

然而,更传统的方法是使用make:

eventDataJSON := make(GITHUB_EVENT, 0)

eventDataJSON 声明为 GITHUB_EVENT,并将其初始化为空 slice 。 (请记住,make 用于特殊的内置类型,例如 slice 、映射和 channel )。

您可以将指向此 slice 的指针传递给 json.Unmarshal:

_ = json.Unmarshal([]byte(eventDataRAW), &eventDataJSON)

...然后直接索引 slice :

fmt.Println(eventDataJSON[0].Id)

此外,json.Marshal 将负责分配输出值,因此您可以声明 eventDataJSON 并跳过任何显式初始化:

var eventDataJSON GITHUB_EVENT

示例:http://play.golang.org/p/zaELDgnpB2

关于json - 将 []struct 与 Json 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27845726/

相关文章:

c - 制作 makefile const 声明和结构问题时出错

c++ - 按值将类型结构传递给函数,错误 :two or more data types in declaration of 'average' !! -

go - := operator and if statement in Golang

go - go get 取包时如何切换到golang.google.cn?

android延迟加载不在手机上显示图像或显示并且速度很慢

java - 尝试 writeValueAsString 时抛出 JsonProcessingException

json - 使用 Select-Object 从 JSON 中提取嵌套字段

javascript - 在 JavaScript 中解析格式错误的 JSON

c - Eclipse CDT 内容协助未完成结构

go - 有什么方法可以在 Go 中动态解析 C 结构吗?