使用Mysql在Go中创建父子嵌套的json

时间:2018-09-26 11:08:30

标签: mysql json go

我正在将golang(go)用于mysql数据库。下面是我的树形视图的数据库结构

ScreenID        ParentID        ScreenName

1                0               Home

2                0               Run Records

3                0               Requests

4                3               NDR

5                4               Add NDR Request

我正在使用的结构是:

type Screens struct {
    ProductID int
    ParentID   int
    ScreenName string
    Children []Screens
}

下面是我的golang代码

db, err := sql.Open("mysql", username + ":" + password + "@tcp(127.0.0.1:3306)/" + dbName)

rows, err := db.Query("call usp_select_screens(1)")

for rows.Next() {
err := rows.Scan(&screens.ProductID, &screens.ParentID, &screens.ScreenName)

我正在尝试将查询结果存储为json。在获取输出并将其编组为json格式时,我需要一些指导:

[  
     {  
        "ParentId":"0",
        "ScreenId":"1",
        "Name":"Home"
    },
    {  
        "ParentId":"0",
        "ScreenId":"2",
        "Name":"Run Records"
    },
    {  
        "ParentId":"0",
        "ScreenId":"3",
        "Name":"Requests",
        "Children":[  
            {  
                "Name":"NDR",
                "ScreenId":"4",
                "ParentId":"3",
                "Children":[  
                    {  
                        "Name":"Add NDR Request",
                        "ScreenId":"5",
                        "ParentId":"4"
                    }
                ]
            }
        ]
    }
]

1 个答案:

答案 0 :(得分:0)

通常,我将标记分配给该结构,然后您可以轻松地使用json.Marshal将结构转换为json格式。

将您的结构更新为:

type Screens struct {
    ParentID int      `json:"ParentId" db:"ParentID"`
    ScreenID int      `json:"ScreenId" db:"ScreenID"`
    Name     string   `json:"Name" db:"ScreenName"`
    Children []Screens `json:"Children,omitempty"`
}

然后将数据扫描到struct :(未经测试)

for rows.Next() {
    if err := rows.Scan(&screens); err != nil {
        // break and handle err
    }
} 

然后转换为JSON:

s, err := json.Marshal(screens)
if err != nil {
    // handle error
}
fmt.Println(string(s))

结果:

{"ParentId":0,"ScreenId":2,"Name":"Home","Children":[{"ParentId":3,"ScreenId":4,"Name":"NDR"}]}

Go Playground - https://play.golang.org/p/KgpC7tFJ_hR