dongzong7467 2018-07-30 08:37
浏览 22
已采纳

Golang Facebook对结构的回应

Hi there I'm new in GO and I'm trying to convert a json from the facebook api to struct.

The problem is that the keys of the object are dinamic:

{
  "100555213756790": {
    "id": "100555213756790",
    "about": "Noodle Bar & Restaurant",
    "metadata": {
      "fields": [
        {
          "name": "id",
          "description": "asdasdasdasd",
          "type": "numeric string"
        },
        //...
  ,
  "101285033290986": {
    "id": "101285033290986",
    "about": "Smart City Expo World Congress",
    "metadata": {
      "fields": [
        {
          "name": "id",
          "description": "fgddgdfgdg",
          "type": "numeric string"
        },

what I have achieved so far is extract the objects by id and turn them into a map:

for _, id := range ids {
    fbPages, ok := results[string(id)].(map[string]interface{})
    if ok {
        for k, v := range fbPages {
            fmt.Println(k)
            fmt.Println(v)
        }
    }
}

//json to Page struct?
    type Page struct {
        ID                string   `json:"id"`
        About             string   `json:"about"`
    }

    type Metadata struct {
        Fields      []Field           `json:"fields"`
        Type        string            `json:"type"`
        Connections map[string]string `json:"connections"`
    }

    type Field struct {
        Name        string  `json:"name"`
        Description string  `json:"description"`
        Type        *string `json:"type,omitempty"`
    }

My question is:

how can I convert that map to struct? or is there any easy way to do what I'm trying to do?

Thank you

  • 写回答

1条回答 默认 最新

  • dongyang9813 2018-07-30 08:59
    关注

    Converting map to struct:

    import "github.com/mitchellh/mapstructure"
    
    mapstructure.Decode(myMap, &myStruct)
    

    example

    But I would do this:

    type Page struct {
        ID                string   `json:"id"`
        About             string   `json:"about"`
        //other fields and nested structs like your metadata struct
    }
    type fbPages map[string]Page
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题