dongshi7350 2018-08-12 22:35
浏览 43


I am trying to decode a map[string]interface{} to a struct, but the "hours" field is not getting populated. I am using for decoding. This is the struct:

BusinessAddRequest struct {
        Name       string `json:"name"`
        Phone      string `json:"phone"`
        Website    string `json:"website,omitempty"`
        Street     string `json:"street"`
        City       string `json:"city"`
        PostalCode string `json:"postalCode"`
        State      string `json:"state"`
        Hours []struct {
            Day                 string `json:"day"`
            OpenTimeSessionOne  string `json:"open_time_session_one,omitempty"`
            CloseTimeSessionOne string `json:"close_time_session_one,omitempty"`
            OpenTimeSessionTwo  string `json:"open_time_session_two,omitempty"`
            CloseTimeSessionTwo string `json:"close_time_session_two,omitempty"`
        } `json:"hours"`
        Cuisine []string `json:"cuisine,omitempty"`
        BusinessID int `json:"businessId,omitempty"`
        AddressID  int `json:"addressId,omitempty"`
        UserID     int `json:"userId,omitempty"`

And this is the example data:

    "name": "Agave ...",
    "phone": "(408) 000-000",
    "street": "Abcd",
    "city": "San",
    "postalCode": "90000",
    "state": "CA",
    "hours": [
        "day": "monday",
        "open_time_session_one": "10:00",
        "close_time_session_one": "21:00"
    "cuisine": [
      "Mexican, tacos, drinks"
    "userId": 1

All fields are getting populated except "hours".

  • 写回答

1条回答 默认 最新

  • dtpfia3334 2018-08-12 23:21

    It could be that you're decoding multiple times into the same BusinessAddRequest variable. Note this doesn't work well when you have structure elements that are slices or maps (this applies BOTH to the mapstructure package and to encoding/json as well!). Always use an empty new variable. If the repetition happens in a loop, declare the variable that you decode to in the loop body (it will be a new copy every time you run through the loop).

    package main
    import "encoding/json"
    import "fmt"
    import ""
    /* (your struct declaration not quoting it to save space) */
    func main() {
        var i map[string]interface{}
        config := &mapstructure.DecoderConfig{
            TagName: "json",
        plan, _ := ioutil.ReadFile("zzz")
        var data []interface{}
        /*err :=*/ json.Unmarshal(plan, &data)
        for j := 0; j < len(data); j++ {
            i = data[j].(map[string]interface{})
            var x BusinessAddRequest /* declared here, so it is clean on every loop */
            config.Result = &x
            decoder, _ := mapstructure.NewDecoder(config)
    ", x)

    (note I had to use a DecoderConfig with TagName="json" to be able to use your structure definition, which is tagged with "json:" and not "mapstructure:").

    If this doesn't help, please check your own code and try to find a minimal example similar to what I posted here that reproduces your problem and add it to the question.

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



  • ¥15 workstation加载centos进入emergency模式,查看日志报警如图,怎样解决呢?
  • ¥50 如何用单纯形法寻优不能精准找不到给定的参数,并联机构误差识别,给定误差有7个?matlab
  • ¥15 workstation加载centos进入emergency模式,查看日志报警如图,没有XFS,怎样解决呢?
  • ¥15 应用商店如何检测在架应用内容是否违规?
  • ¥15 Ubuntu系统配置PX4
  • ¥50 nw.js调用activex
  • ¥15 数据库获取信息反馈出错,直接查询了ref字段并且还使用了User文档的_id而不是自己的
  • ¥15 将安全信息用到以下对象时发生以下错误:c:dumpstack.log.tmp 另一个程序正在使用此文件,因此无法访问
  • ¥15 速度位置规划实现精确定位的问题
  • ¥15 MAC虚拟机(win11)USB插上后无串口com,无法烧录