dsizd368332 2018-08-18 00:34
浏览 56
已采纳

动态JSON结构,API结果golang

I have to make two HTTP API calls in GoLang, the first API call returns this json response:

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

My json struct for first response is setup like this:

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

The second call is where the problem is. As you can see the first API call returns a result -> id. This ID should be the name for the beginning of my second struct, but I can't seem how to make it dynamic or put a result as my structure name. This ID (24) will always change based on the first API call. I have no way currently to parse the second call's JSON and setup my struct. On the second API call I want to access the remoteurl/status.

Second call result (I can not parse):

{
  "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
    }
  }
}

Does anyone know how to setup my struct or go about this. I am a new programmer and go and have worked on this for 4 days. And decided to ask for some help, since I am in school and have normal homework.

  • 写回答

1条回答 默认 最新

  • douxing2652 2018-08-18 03:00
    关注
    {
      "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
        }
      }
    }
    

    Is not value JSON. You MUST mean the JSON i posted below, if you want to check yourself, copy your version of the JSON into any JSON validator;

    https://jsonlint.com/

    https://jsoneditoronline.org/

    https://jsonformatter.curiousconcept.com/

    Also view the thread linked below.. if the API truly is returning what you claim it returns then the API has a bug in it

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

    Here is some example code that uses a map to a struct what solves the dynamic response of the second response

    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 
    
    ", b)
        b, _ = json.MarshalIndent(two, "", " ")
        fmt.Printf("%s 
    
    ", 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
    %s
    ", b)
        }
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条