duanhui9840 2019-08-25 01:45
浏览 41
已采纳

解码JSON值的更好方法

Assume a JSON object with the general format

  "accounts": [
    {
      "id": "<ACCOUNT>", 
      "tags": []
    }
  ]
}

I can create a struct with corresponding json tags to decode it like so

 type AccountProperties struct {
    ID AccountID `json:"id"`
    MT4AccountID int `json:"mt4AccountID,omitempty"`
    Tags []string `json:"tags"`
  }

  type Accounts struct {
    Accounts []AccountProperties `json:"accounts"`
  }

But the last struct with just one element seems incorrect to me. Is there a way I could simply say type Accounts []AccountProperties `json:"accounts"` instead of creating an entire new struct just to decode this object?

  • 写回答

1条回答 默认 最新

  • dongzhong5756 2019-08-25 02:04
    关注

    You need somewhere to store the json string accounts. Using a:

    var m map[string][]AccountProperties
    

    suffices, though of course you then need to know to use the string literal accounts to access the (single) map entry thus created:

    type AccountProperties struct {
        ID           string   `json:"id"`
        MT4AccountID int      `json:"mt4AccountID,omitempty"`
        Tags         []string `json:"tags"`
    }
    
    func main() {
        var m map[string][]AccountProperties
        err := json.Unmarshal([]byte(data), &m)
        fmt.Println(err, m["accounts"])
    }
    

    See complete Go Playground example (I had to change the type of ID to string and fix the missing { in the json).


    As Dave C points out in comments, this is no shorter than just using an anonymous struct type:

    var a struct{ Accounts []AccountProperties }
    

    in terms of the Unmarshall call (and when done this way it's more convenient to use). Should you want to use an anonymous struct like this in a json.Marshall call, you'll need to tag its single element to get a lowercase encoding: without a tag it will be called "Accounts" rather than "accounts".

    (I don't claim the map method to be better, just an alternative.)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog