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

报告相同问题?

悬赏问题

  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试