登录
首页 >  Golang >  Go问答

如何解组 json 数据以以明确定义的格式打印

来源:stackoverflow

时间:2024-04-08 14:39:32 436浏览 收藏

怎么入门Golang编程?需要学习哪些知识点?这是新手们刚接触编程时常见的问题;下面golang学习网就来给大家整理分享一些知识点,希望能够给初学者一些帮助。本篇文章就来介绍《如何解组 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)
    }

}

在评估“read”之前,代码运行良好,但在使用 json.unmarshal 时抛出以下错误“json:无法将对象解组为 main.post[] 类型的 go 值”


解决方案


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

}

本篇关于《如何解组 json 数据以以明确定义的格式打印》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>