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条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!