Home > Net >  Filter JSON returned from GitHub API via Go
Filter JSON returned from GitHub API via Go

Time:06-01

I'm trying to get the latest release information from a github repository and grab a specific asset in that release. The following code prints out the release tag and the all the assets under the Asset structure. I'd like to be able to pull out a specific item and its download url, such as just the ajour.exe tag. Can I do that via the struct, or should I be parsing the output to grab it?

func GetGithubAsset() {
    testUri := "https://api.github.com/repos/ajour/ajour/releases/latest"
    type githubApiData struct {
       AppVersion string `json:"tag_name"`
       Assets     []struct {
          Name               string `json:"name"`
          BrowserDownloadURL string `json:"browser_download_url"`
       }
    }
    resp, err := http.Get(testUri)
    if err != nil {
        log.Fatal(err)
    }
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        log.Fatal(err)
    }
    var data githubApiData
    jsonErr := json.Unmarshal(body, &data)
    if jsonErr != nil {
        log.Fatal(jsonErr)
    }
    fmt.Println(data.AppVersion)
    fmt.Println(data.Assets)
}

CodePudding user response:

You're almost there. Note that the json.Unmarshal does parse the output for you. All you need to is loop through the Assets field, something like so (in place of fmt.Println(data.Assets)):

    for _, asset := range data.Assets {
        if asset.Name == "ajour.exe" {
            fmt.Println(asset.BrowserDownloadURL)
        }
    }

CodePudding user response:

The json tag json:"assets" is missing

func GetGithubAsset() {
    testUri := "https://api.github.com/repos/ajour/ajour/releases/latest"
    type githubApiData struct {
        AppVersion string `json:"tag_name"`
        Assets     []struct {
            Name               string `json:"name"`
            BrowserDownloadURL string `json:"browser_download_url"`
        } `json:"assets"`
    }
    resp, err := http.Get(testUri)
    if err != nil {
        log.Fatal(err)
    }
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        log.Fatal(err)
    }
    var data githubApiData
    jsonErr := json.Unmarshal(body, &data)
    if jsonErr != nil {
        log.Fatal(jsonErr)
    }
    fmt.Println(data.AppVersion)
    fmt.Println(data.Assets)
}
  •  Tags:  
  • go
  • Related