首页 > 解决方案 > 如何解组 json 数据以明确定义的格式打印

问题描述

我不知道如何解组 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)
    }

}

在评估“读取”之前代码运行良好,但在使用 json.Unmarshal “json: cannot unmarshal object into Go value of type main.post[]”时抛出以下错误

标签: jsonapigounmarshalling

解决方案


您需要创建第二个结构来接收整个 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)
    }

}

推荐阅读