登录
首页 >  Golang >  Go问答

使用Golang处理动态JSON结构的API响应

来源:stackoverflow

时间:2024-03-02 08:27:29 376浏览 收藏

积累知识,胜过积蓄金银!毕竟在Golang开发的过程中,会遇到各种各样的问题,往往都是一些细节知识点还没有掌握好而导致的,因此基础知识点的积累是很重要的。下面本文《使用Golang处理动态JSON结构的API响应》,就带大家讲解一下知识点,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

问题内容

我必须在 golang 中进行两次 http api 调用,第一个 api 调用返回此 json 响应:

{
  "status": 200,
  "msg": "ok",
  "result": {
    "id": "24",
    "folderid": "4248"
  }
}

我的第一个响应的 json 结构设置如下:

type one struct {
    status int    `json:"status"`
    msg    string `json:"msg"`
    result struct {
        id       string `json:"id"`
        folderid string `json:"folderid"`
    } `json:"result"`
}

第二个调用就是问题所在。正如您所看到的,第一个 api 调用返回结果 -> id。这个 id 应该是我的第二个结构的开头的名称,但我似乎无法使其动态或将结果作为我的结构名称。此 id (24) 将始终根据第一次 api 调用而更改。我目前无法解析第二个调用的 json 并设置我的结构。在第二次 api 调用中,我想访问 remoteurl/status。

第二次调用结果(我无法解析):

{
  "status": 200,
  "msg": "OK",
  "result": {
    24: ** THIS IS DYNAMIC** {
      "id": 24,
      "remoteurl": "http://proof.ovh.net/files/100Mio.dat",
      "status": "new",
      "bytes_loaded": null,
      "bytes_total": null,
      "folderid": "4248",
      "added": "2015-02-21 09:20:26",
      "last_update": "2015-02-21 09:20:26",
      "extid": false,
      "url": false
    }
  }
}

有谁知道如何设置我的结构或进行此操作。我是一名新程序员,已经为此工作了 4 天。并决定寻求一些帮助,因为我在学校并且有正常的作业。

发现使用 json-to-go 有助于解决未来的问题,将根据 json 内容创建结构和其他必需品。


解决方案


{
  "status": 200,
  "msg": "ok",
  "result": {
    24:  {
      "id": 24,
      "remoteurl": "http://proof.ovh.net/files/100mio.dat",
      "status": "new",
      "bytes_loaded": null,
      "bytes_total": null,
      "folderid": "4248",
      "added": "2015-02-21 09:20:26",
      "last_update": "2015-02-21 09:20:26",
      "extid": false,
      "url": false
    }
  }
}

不是值 json。您必须指的是我在下面发布的 json,如果您想自行检查,请将您的 json 版本复制到任何 json 验证器中;

https://jsonlint.com/

https://jsoneditoronline.org/

https://jsonformatter.curiousconcept.com/

另请查看下面链接的线程。如果 api 确实返回了您声称返回的内容,那么该 api 中存在错误

Why JSON allows only string to be a key?

{
  "status": 200,
  "msg": "ok",
  "result": {
    "24":  {
      "id": 24,
      "remoteurl": "http://proof.ovh.net/files/100mio.dat",
      "status": "new",
      "bytes_loaded": null,
      "bytes_total": null,
      "folderid": "4248",
      "added": "2015-02-21 09:20:26",
      "last_update": "2015-02-21 09:20:26",
      "extid": false,
      "url": false
    }
  }
}

这里是一些示例代码,它使用结构的映射来解决第二个响应的动态响应

package main

import (
    "encoding/json"
    "fmt"
    "log"
)

var res1 = `{
  "status": 200,
  "msg": "OK",
  "result": {
    "id": "24",
    "folderid": "4248"
  }
}`

var res2 = `{
  "status": 200,
  "msg": "OK",
  "result": {
    "24":  {
      "id": 24,
      "remoteurl": "http://proof.ovh.net/files/100Mio.dat",
      "status": "new",
      "bytes_loaded": null,
      "bytes_total": null,
      "folderid": "4248",
      "added": "2015-02-21 09:20:26",
      "last_update": "2015-02-21 09:20:26",
      "extid": false,
      "url": false
    }
  }
}
`

type One struct {
    Status int    `json:"status"`
    Msg    string `json:"msg"`
    Result struct {
        ID       string `json:"id"`
        Folderid string `json:"folderid"`
    } `json:"result"`
}

type Two struct {
    Status int                  `json:"status"`
    Msg    string               `json:"msg"`
    Result map[string]innerData `json:"result"`
}

type innerData struct {
    ID          int         `json:"id"`
    Remoteurl   string      `json:"remoteurl"`
    Status      string      `json:"status"`
    BytesLoaded interface{} `json:"bytes_loaded"`
    BytesTotal  interface{} `json:"bytes_total"`
    Folderid    string      `json:"folderid"`
    Added       string      `json:"added"`
    LastUpdate  string      `json:"last_update"`
    Extid       bool        `json:"extid"`
    URL         bool        `json:"url"`
}

func main() {
    var one One
    err := json.Unmarshal([]byte(res1), &one)
    if err != nil {
        log.Fatal(err)
    }

    var two Two
    err = json.Unmarshal([]byte(res2), &two)
    if err != nil {
        log.Fatal(err)
    }

    //pretty print both strutures
    b, _ := json.MarshalIndent(one, "", " ")
    fmt.Printf("%s \n\n", b)
    b, _ = json.MarshalIndent(two, "", " ")
    fmt.Printf("%s \n\n", b)

    // access data from two with id from one
    if dat, ok := two.Result[one.Result.ID]; ok {
        b, _ = json.MarshalIndent(dat, "", " ")
        fmt.Printf("inner data\n%s\n", b)
    }

}

今天关于《使用Golang处理动态JSON结构的API响应》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

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