Как распаковать данные JSON для печати в четко определенном формате - PullRequest
0 голосов
/ 11 февраля 2019

Я не могу понять, как распаковать данные json, предоставленные API-интерфейсом, и использовать эти данные для печати в указанном формате.

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

type postOffice []struct {
    Name    string
    Taluk   string
    Region  string
    Country string
}

func main() {
    data, err := http.Get("http://postalpincode.in/api/pincode/221010")
    if err != nil {
        fmt.Printf("The http request has a error : %s", err)
    } else {
        read, _ := ioutil.ReadAll(data.Body)
        var po postOffice
        err = json.Unmarshal(read, &po)
        if err != nil {
            fmt.Printf("%s", err)
        }
        fmt.Print(po)
    }

}

Код работал хорошо, пока "чтение" не быловычисляется, но выдает следующую ошибку при использовании json.Unmarshal "json: не может демонтировать объект в значение Go типа main.post []"

1 Ответ

0 голосов
/ 11 февраля 2019

Вам нужно создать вторую структуру для получения всего JSON.

type JSONResponse struct {
    Message    string     `json:"Message"`
    Status     string     `json:"Success"`
    PostOffice postOffice `json:"PostOffice"`
}

Это потому, что PostOffice является массивом внутри ответа.

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

//this is the new struct
type JSONResponse struct {
    Message    string     `json:"Message"`
    Status     string     `json:"Success"`
    PostOffice postOffice `json:"PostOffice"`
}

type postOffice []struct {
    Name    string
    Taluk   string
    Region  string
    Country string
}

func main() {
    data, err := http.Get("http://postalpincode.in/api/pincode/221010")
    if err != nil {
        fmt.Printf("The http request has a error : %s", err)
    } else {
        read, _ := ioutil.ReadAll(data.Body)
        //change the type of the struct
        var po JSONResponse
        err = json.Unmarshal(read, &po)
        if err != nil {
            fmt.Printf("%s", err)
        }
        fmt.Print(po)
    }

}
...