如何将json数据解组以定义良好的格式打印

如何将json数据解组以定义良好的格式打印,json,api,go,unmarshalling,Json,Api,Go,Unmarshalling,我不知道如何解组api提供的json数据并使用数据以指定格式打印 package main import ( "encoding/json" "fmt" "io/ioutil" "net/http" ) type postOffice []struct { Name string Taluk string Region string Country string } func main() { data,

我不知道如何解组api提供的json数据并使用数据以指定格式打印

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)
    }

}

在计算“read”之前,代码运行良好,但在使用json时抛出以下错误。Unmarshal“json:无法将对象解组到main.post[]类型的Go值中”

您需要创建第二个结构来接收整个json

type JSONResponse struct {
    Message    string     `json:"Message"`
    Status     string     `json:"Success"`
    PostOffice postOffice `json:"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)
    }

}

JSON对象必须解组为结构值或映射,但您有一个切片值(仅适用于JSON数组)。