duanbi3385 2018-04-27 19:59 采纳率: 100%
浏览 1661
已采纳

golang为类型为map [string] interface {}的对象设置新值

I got json str which i parse like this.

var bdoc interface{}
bson.UnmarshalJSON([]byte(gjson.Get(*str, "user").String()), &bdoc)

my bdoc is of type map[string]interface{}. When i want to get key from my map i do it like this:

bdoc.(map[string]interface{})["pk"]

But how can i set a new value for that "pk" key ? I want to convert that bdoc["pk"] = "1234567". The new value will not be of type interface but of type string.

  • 写回答

1条回答 默认 最新

  • doulue7522 2018-04-27 20:44
    关注

    You can set string and value stay as string type

    package main
    
    import (
        "fmt"
        "log"
    )
    
    func main() {
    
        var bdoc interface{}
        aMap, ok := bdoc.(map[string]interface{})
        if !ok {
           log.Fatalf("Failed to cast %T", bdoc)
        }
        //depending on JSON settting pk number may have json.Numbe or float64
        fmt.Prinf("%v  %T
    ", aMap["pk"], aMap["pk"])
       aMap["pk"] ="1234"
        fmt.Prinf("%v  %T
    ", aMap["pk"], aMap["pk"])
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

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