dtby67541 2014-10-03 14:28
浏览 148
已采纳

使用Go解析复杂的JSON

I'm having issues digesting some nested JSON with Go. My primary issue is that I can't model my struct correctly to try and get the library to pull any information in. Here is a sample of the JSON data: http://pastebin.com/fcGQqi5z

The data is from a bank and has been scrubbed for privacy. Ideally I'm only interested in the transactions ID, the amount, and the description. Is there a way to just pull these values with Go?

This was my initial attempt:

type Trans struct {
  TransId string
  Amount int
  Description string
}
  • 写回答

2条回答 默认 最新

  • dqf2015 2014-10-03 14:52
    关注

    You were on the right tracks:

    type Trans struct {
        TransId     string
        Amount      float64
        Description string
    }
    
    func main() {
        var data struct {
            Record []Trans
        }
        if err := json.Unmarshal([]byte(j), &data); err != nil {
            fmt.Println(err)
            return
        }
        fmt.Printf("%#v
    ", data.Record)
    }
    

    <kbd>playground</kbd>

    //edit

    type Trans struct {
        TransId     string
        Amount      float64
        Description string
        RawInfo     []map[string]json.RawMessage `json:"AdditionalInfo"`
    }
    
    // also this assumes that 1. all data are strings and 2. they have unique keys
    // if this isn't the case, you can use map[string][]string or something
    func (t *Trans) AdditionalInfo() (m map[string]string) {
        m = make(map[string]string, len(t.RawInfo))
        for _, info := range t.RawInfo {
            for k, v := range info {
                m[k] = string(v)
            }
        }
        return
    }
    

    <kbd>playground</kbd>

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 Macbookpro 连接热点正常上网,连接不了Wi-Fi。
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程