doujiu8479 2016-03-16 16:51
浏览 104
已采纳

如何在golang中定义此类型的数据

I have a data like '{"{\"hello\":\"world\"}"}', it's a array json in postgresql.

I don't know how to handle it in golang. I know I can define with string then use json.Unmarshal to slove, but I want to know if there is a way to get it in a struct

  • 写回答

1条回答 默认 最新

  • douyi6818 2016-03-16 17:46
    关注

    I assume you posted incorrect JSON and let's say it's '{"hello": "world"} A struct has a predefined fields, and with arbitrary JSON coming in it's impossible to know ahead. The possible solution would be to convert it into a map.

    var data interface{}
    b := []byte(`{"hello": "world"}`)
    err := json.Unmarshal(b, &data)
    if err != nil {
            panic(err)
    }
    fmt.Print(data)
    

    As you print out the data, you'll probably get something like. map[hello:world]

    Which is in the form of map[string]interface{}.

    Then you can use type switch to loop into the map structure until you type assert all the interface{}.

    for k, v := range data.(map[string]interface{}) {
            switch val := v.(type) {
            case string:
                    v = val
            default:
                    fmt.Println(k, "is unknown type")
            }
    }
    

    Map is an ideal data structure when dealing with arbitrary incoming JSON. However, if the JSON is generated from an SQL table with predefined schemas, you can use a struct with the same structure instead of a map.

    type Hello struct {
            Hello string `json:"hello"`
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,
  • ¥15 spaceclaim模型变灰色