How to format json with html/template

hello!
I would like to use the json output of a GET request to create a sort of html table but I don’t know how to do that.
My code is the following:

package main

import (

"encoding/json"

"fmt"

"html/template"

"net/http"

"os"

"time"

 )

var answer string

type AutoGenerated struct {

Latest    Latest      `json:"latest"`

Locations []Locations `json:"locations"`

}

type Latest struct {

Confirmed int `json:"confirmed"`

Deaths    int `json:"deaths"`

Recovered int `json:"recovered"`

}

type Coordinates struct {

Latitude  string `json:"latitude"`

Longitude string `json:"longitude"`

}

type Locations struct {

ID          int         `json:"id"`

Country     string      `json:"country"`

CountryCode string      `json:"country_code"`

Province    string      `json:"province"`

LastUpdated time.Time   `json:"last_updated"`

Coordinates Coordinates `json:"coordinates"`

Latest      Latest      `json:"latest"`

}

var baseUrl = "https://coronavirus-tracker-api.herokuapp.com/v2"

var latestUrl = "/locations"

 func getJson(url string, target interface{}) error {

req, err := http.NewRequest("GET", url, nil)

if err != nil {

    fmt.Println(err)

}

req.Header.Add("content-type", "application/json")

res, err := http.DefaultClient.Do(req)

if err != nil {

    fmt.Println(err)

    //return err.Error()

}

defer res.Body.Close()

return json.NewDecoder(res.Body).Decode(target)

}

var dataPage = `<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title></title>

</head>

<body>

<ul>

{{range .}}

    <li>

        <span>{{.Country}} </span>

    </li>

{{end}}

</ul>

</body>

</html>`

 func main() {

var locationsUrl = baseUrl + latestUrl

var data AutoGenerated

getJson(locationsUrl, &data)

fmt.Printf("%+v\n", data)

tmp, err := template.New("data").Parse(dataPage)

if err != nil {

    panic(err)

}

tmp.Execute(os.Stdout, data)

}

The idea is to get something like this:
https://coronavirus-tracker-api.herokuapp.com/v2/locations

I’ve tried to use html/template to have alist of the country printed on the html in the stdout but I didn’t get anything

Thanks

What exactly is not working? Do you get an error? What output do you get, what do you expect?

hi
I took inspiration from this https://play.golang.org/p/EYfV-TzoA0
I was expecting to get in the output something like this

	<li>
		<span>Italy</span>
	</li>

	<li>
		<span>Spain</span>
	</li>
</ul>

The JSON object returned from https://coronavirus-tracker-api.herokuapp.com/v2/locations has two members, latest and locations. Your HTML template looks like you want to loop over locations. Do this:

tmp.Execute(os.Stdout, data.Locations)
2 Likes

thank you very much!