dongshi7350 2018-08-12 22:35
浏览 43
已采纳

Golang地图结构未按预期工作

I am trying to decode a map[string]interface{} to a struct, but the "hours" field is not getting populated. I am using https://github.com/mitchellh/mapstructure 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 "github.com/mitchellh/mapstructure"
    
    /* (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)
            decoder.Decode(i)
            fmt.Printf("%+v
    ", 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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵