hyousef
(Hasan Yousef)
October 19, 2020, 2:27pm
1
I want to return the string returned from this link , and build a JSON object based on the returned data, I wrote the below code that is reading the url and getting the string correctly, but it fails in building the JSON object, and do not return anything!
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
)
type Product struct {
ProductId string `json:"id"`
ProductName string `json:"description"`
}
func main() {
url := "https://script.googleusercontent.com/macros/echo?user_content_key=WBSJPDNSN6X1FCYeXsR6TDaDval0vdvmSoMmXFhGbt5sfK0ia80Dp7kPD27GLpZbYz8vrwfDiUecI2oGMjEtgfL5o8Da25T1m5_BxDlH2jW0nuo2oDemN9CCS2h10ox_1xSncGQajx_ryfhECjZEnGb6k9xaGtOX6M1tIiG811CRpk9nXl8ZKS7UJTno1dvQXMe1kqfAj8WxsSkLor-EqzOmbnRGq-tk&lib=M0B6GXYh0EOYMkP7qr1Xy9xw8GuJxFqGH"
resp, err := http.Get(url)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
htmlData, err := ioutil.ReadAll(resp.Body) //<--- here!
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// print out
fmt.Println(string(htmlData))
var product Product
json.Unmarshal([]byte(string(htmlData)), &product)
fmt.Printf("ID: %s, Description: %s", product.ProductId, product.ProductName)
}
Output:
{"user":[{"ProductId":1,"ProductName":"Helmet"},{"ProductId":2,"ProductName":"Glove"},{"ProductId":3,"ProductName":"Detecttor"}]}
ID: , Description:
hyousef
(Hasan Yousef)
October 19, 2020, 4:28pm
2
I got it:
1- The unmarshal target struct must match the data,
type Data struct {
User []Product `json:"user"`
}
2- The fields types should be matching, so ProductID
should be uint
3- The json OP got in output should match the tags used
type Product struct {
ProductId uint `json:"ProductId"`
ProductName string `json:"ProductName"`
}
So, a working code is:
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
)
type Data struct {
User []Product `json:"user"`
}
type Product struct {
ProductId uint `json:"ProductId"`
ProductName string `json:"ProductName"`
}
func main() {
url := "https://script.googleusercontent.com/macros/echo?user_content_key=WBSJPDNSN6X1FCYeXsR6TDaDval0vdvmSoMmXFhGbt5sfK0ia80Dp7kPD27GLpZbYz8vrwfDiUecI2oGMjEtgfL5o8Da25T1m5_BxDlH2jW0nuo2oDemN9CCS2h10ox_1xSncGQajx_ryfhECjZEnGb6k9xaGtOX6M1tIiG811CRpk9nXl8ZKS7UJTno1dvQXMe1kqfAj8WxsSkLor-EqzOmbnRGq-tk&lib=M0B6GXYh0EOYMkP7qr1Xy9xw8GuJxFqGH"
resp, err := http.Get(url)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
htmlData, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// print out
fmt.Println(string(htmlData))
//var product Product
var data Data
json.Unmarshal([]byte(string(htmlData)), &data)
fmt.Println(data)
fmt.Println(data.User)
fmt.Println(data.User[0])
fmt.Printf("id: %v, description: %s", data.User[0].ProductId, data.User[0].ProductName)
}
system
(system)
Closed
January 17, 2021, 4:28pm
3
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.