douju6651 2017-03-20 23:54
浏览 32
已采纳

没有要构造的键/值的Golang解组数组

I'm trying to place a json array into a struct from Google Analytics API.

EG:

"rows": [
    [
        "female",
        "18-24",
        "1308"
    ],
    [
        "female",
        "25-34",
        "741"
    ]
]

Typically I'd have key/value so I can put json:"gender" but there are no keys to associate with, so the values that it would search for change.

The struct would be:

type Row struct {
    Gender   string `json:"gender"`
    AgeRange string `json:"blah"`
    Count    string `json:"blah"`
}

If I do len(jResp.Rows) I can see that it's grabbing all twelve rows/arrays but the fields are empty.

  • 写回答

1条回答 默认 最新

  • dongyunwei8596 2017-03-21 00:11
    关注

    I don't think it's possible, with encoding/json to directly decode that json into a slice of structs without first implementing a UnmarshalJSON method on your Row type.

    func (r *Row) UnmarshalJSON(data []byte) error {
         var s []string
         if err := json.Unmarshal(data, &s); err != nil {
              return err
         }
         if len(s) >= 3 {
             r.Gender = s[0]
             r.AgeRange = s[1]
             r.Count = s[2]
         }
         return nil
    }
    
    // make sure it's a slice of pointers to Row
    type Resp struct {
        Rows []*Row `json:"rows"`
    }
    

    Edit: fixed the code a little to make it actually compile. Heres a working example https://play.golang.org/p/eqVQj65xJv.

    You could also just decode the data first into a slice of strings and then loop over the result to build you struct values.

    type Resp struct {
        Rows [][]string `json:"rows"`
    }
    
    type Row struct {
        Gender   string `json:"gender"`
        AgeRange string `json:"blah"`
        Count    string `json:"blah"`
    }
    
    var resp jResp
    if err := json.Unmarshal(data, &resp); err != nil {
        panic(err)
    }
    
    var rows = make([]Row, len(resp.Rows))
    for i, r := range resp.Rows {
        rows[i] = Row{
            Gender: r[0],
            AgeRange: r[1],
            Count: r[2],
        }
    }
    

    Edit: fixed this one as well. https://play.golang.org/p/Otb7iULSh3

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度