doushi8187 2018-07-12 03:17
浏览 59
已采纳

如何在对象具有字符串键的Golang中解组JSON

I have some JSON that looks like this:

{
  "ABC": {"symbol": "abc", "open": 42},
  "DEF": {"symbol": "abc", "open": 42},
  "GHI": {"symbol": "abc", "open": 42}
}

And I don't need the ABC/DEF/GHI part, only the part on the right. The values of ABC, DEF, and GHI are of type entity.Day in my code, which looks something like this:

type Day struct {
    Symbol           string    `json:"symbol"  sql:"symbol"`
    Date             time.Time `json:"date"  sql:"date"`
    OpenP            float64   `json:"open"  sql:"open"`
    HighP            float64   `json:"high"  sql:"high"`
    LowP             float64   `json:"low"  sql:"low"`
    CloseP           float64   `json:"close"  sql:"close"`
    VolumeP          float64   `json:"volume"  sql:"volume"`
    Label            string    `json:"label" sql:"-"`
    ChangeOverTime   float64   `json:"changeOverTime"  sql:"change_over_time"`
    UnadjustedVolume float64   `json:"unadjustedVolume"  sql:"unadjusted_volume"`
    Change           float64   `json:"change"  sql:"change"`
    ChangePercent    float64   `json:"changePercent"  sql:"change_percent"`
    VWAP             float64   `json:"vwap"  sql:"vwap"`
}

There are other endpoints that produce entity.Days, however this is the only one that's structured like this. How can I unmarshal the JSON into, ideally, an array of entity.Days?

My first thought was to make an intermediate data structure:

type previous struct {
    tckrs map[string]entity.Day
}

p := previous{tckrs: make(map[string]entity.Day)}
json.Unmarshal(res, &p)

That code produces an empty struct and json.Unmarshal returns a nil error. Can you help me?

PS - I searched around quite a bit and I found similar answers and lots of other people trying the map approach, although that did not work for me.

  • 写回答

1条回答 默认 最新

  • dpruwm6206 2018-07-12 03:25
    关注

    The type previous you defined would require your JSON to represent an object with one top level field containing the map.

    Since your JSON models a map directly, you can use a map to unmarshal it.

    Try just:

    p := make(map[string]Day)
    json.Unmarshal(res, &p)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,