dongyou8368 2019-04-16 18:31
浏览 487
已采纳

如何解组包含整数,浮点数和数字字符串的JSON?

I have a multiple different JSON requests of data that is being passed into my Go app that contains numbers in different formats. An example of a request is as follows:

{
    "stringData":"123456",
    "intData": 123456,
    "floatData": 123456.0
}

Is there a way to unmarshal this data into the type which is determined by the JSON data. For example, string data would be "123456", int data would be 123456 and float data would be 123456.0. I do not have structs defined for these JSON objects and creating structs for these are not an option.

I have looked at the decoder.UseNumber() method to convert the data into strings, but I don't know how to handle the difference between stringData and intData after that.

  • 写回答

2条回答 默认 最新

  • doujiong9915 2019-04-16 22:59
    关注

    Decode to map[string]interface{} with the UseNumber option. Use a type assertion to find numbers and convert based on presence of the ".".

    dec := json.NewDecoder(r)
    dec.UseNumber()
    
    var m map[string]interface{}
    err := dec.Decode(&m)
    if err != nil {
        log.Fatal(err)
    }
    
    for k, v := range m {
        v, err := decodeValue(v)
        if err != nil {
            log.Fatal(err)
        }
    for k, v := range m {
        v, err := decodeValue(v)
        if err != nil {
            log.Fatal(err)
        }
        switch v := v.(type) {
        case string:
            fmt.Printf("%s is a string with value %q
    ", k, v)
        case int64:
            fmt.Printf("%s is a integer with value %d
    ", k, v)
        case float64:
            fmt.Printf("%s is a float with value %f
    ", k, v)
        default:
            fmt.Printf("%s is a %T with value %v
    ", k, v, v)
        }
    }
    
    
    ...
    
    func decodeValue(v interface{}) (interface{}, error) {
        if vv, ok := v.(json.Number); ok {
            if strings.Contains(vv.String(), ".") {
                return vv.Float64()
            } else {
                return vv.Int64()
            }
        } else {
            return v, nil
        }
    }
    

    Run it on the playground.

    This example prints what's found and exits the program on error. If your goal is to create a map with the values of the correct types, then replace the code that prints numbers with m[k] = n.

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

报告相同问题?

悬赏问题

  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元