dongqian5384 2016-08-18 13:28
浏览 26
已采纳

解组json可选元素Golang

The data I got are xlsx rows in this format: row 1 value 1 is the first cell (A1), row 1 value 2 is the second cell (B1) etc. Any cell can (but doesn't need to) contain styles e.g. Border, Fill etc. .Styles will be in curly brackets like in this data: [[["row 1 value 1",{"Border":null,"Fill":{"arrFill":{"BgColor":"red"}},"Font":null,"ApplyBorder":null}],"row 1 value 2","row 1 value 3"],["row 2 value 1","row 2 value 2","row 2 value 3"]]

How to unmarshal this data to get also the not neccessary style map?

Playground

  • 写回答

1条回答 默认 最新

  • doulaobi7988 2016-08-18 14:58
    关注

    You may need to use the reflect package to check data types in the resulting array/map. It looks tedious, but seems that is the only way out. I have pasted below some quick and dirt, but runnable code to illustrate the same:

    package main
    
    import (
        "encoding/json"
        "fmt"
        "reflect"
    )
    
    func parsePrintArray(y interface{}) {
        var dummy []interface{}
        var dummy2 map[string]interface{}
        if reflect.TypeOf(y) == reflect.TypeOf("") {
            fmt.Printf("%s ", y)
            return
        }
        if reflect.TypeOf(y) == reflect.TypeOf(dummy2) {
            x := y.(map[string]interface{})
            for ks, vi := range x {
                fmt.Printf("
    dumping for key %s ", ks)
                if vi != nil {
                    parsePrintArray(vi)
                }
            }
            return
        }
        for k, yl := range y.([]interface{}) {
            if reflect.TypeOf(yl) == reflect.TypeOf(dummy) {
                fmt.Println("")
                parsePrintArray(yl.([]interface{}))
            } else if reflect.TypeOf(yl) == reflect.TypeOf("") {
                fmt.Printf("%v: %s ", k, yl.(string))
            } else if reflect.TypeOf(yl) == reflect.TypeOf(dummy2) {
                x := yl.(map[string]interface{})
                for ks, vi := range x {
                    fmt.Printf("
    dumping for key %s ", ks)
                    if vi != nil {
                        parsePrintArray(vi)
                    }
                }
            }
        }
    }
    
    func main() {
    
        x := "[[[\"row 1 value1\",{\"Border\":null,\"Fill\":{\"arrFill\":{\"BgColor\":\"red\"}},\"Font\":null,\"ApplyBorder\":null}],\"row 1 value2\",\"row 1 value 3\"],[\"row 2 value 1\",\"row 2 value 2\",\"row 2 value 3\"]]"
    
        var y []interface{}
        err := json.Unmarshal([]byte(x), &y)
        if err != nil {
            panic(err)
        }
        parsePrintArray(y)
        fmt.Println("")
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥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#的问题:自动化测试