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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀