现在,我正在为REST API编写GO
现在,我得到了3个JSON(str_data_table / str_all_col / str_all_domain),如下所示(这些JSON是slice数据类型)
字符串数据表
{
"table" : "tablea",
"table_type" : "pubilc"
}
字符串
str_all_col
[
{
"table" : "tablea",
"field" : "name",
"type". : "string"
},
{
"table" : "tablea",
"field" : "surname"
"type". : "string"
},
]
型
str_all_domain
[
{
"field" : "name",
"domain" : "xxx",
"element" : "jjjjj"
},
{
"field" : "name",
"domain" : "yyyy",
"element" : "ssss"
},
{
"field" : "surname",
"domain" : "aaaaaa",
"element" : "dddd"
},
{
"field" : "surname",
"domain" : "bbbbbb",
"element" : "eeee"
}
]
型
我需要将这3个JSON分组为一个JSON,如下所示
{
"table" : "tablea",
"table_type" : "pubilc"
"field" : [
{
"field" : "name",
"type". : "string",
"detail" : [
{
"domain" : "xxx",
"element" : "jjjjj"
},
{
"domain" : "yyyy",
"element" : "ssss"
}
]
},
{
"field" : "surname",
"type". : "string",
"detail" : [
{
"domain" : "aaaaaa",
"element" : "dddd"
},
{
"domain" : "bbbbbb",
"element" : "eeee"
}
]
}
]
}
型
所以我在GO中使用sqlc / chi-router / postgresql编写代码
type str_domain_into struct {
Domain string
Element string
}
type str_column_info struct {
Field string
Type string
domain []str_domain_into
}
type str_table struct {
Table string
TableType string
column []str_column_info
}
var mixData []str_table
var w_mixData str_table
var w_col str_column_info
var w_domain str_domain_into
for _, dataTable := range str_data_table {
w_mixData.Table = dataTable.Table
w_mixData.TableType = dataTable.TableType
for _, dataColumn := range str_all_col {
if dataTable.Table != dataColumn.Table {
continue
}
w_col.Field = dataColumn.Field
w_col.Type = dataColumn.Type
for _, dataDomain := range str_all_domain {
if dataColumn.Field != dataDomain.Field {
continue
}
w_domain.Domain = dataDomain.Domain
w_domain.Element = dataDomain.Element
w_col.domain = append(w_col.domain, w_domain)
}
w_mixData.column = append(w_mixData.column, w_col)
}
mixData = append(mixData, w_mixData)
}
respondWithJSON(w, 200, mixData)
型
然而,mixData的响应只有如下两个字段
{
"table" : "tablea",
"table_type" : "pubilc"
}
型
func respondWithJSON的附加代码
func respondWithJSON(w http.ResponseWriter, code int, payload interface{}) {
// The payload is struct data
data, err := json.Marshal(payload)
if err != nil {
log.Printf("Failed to marshal JSON response : %v", payload)
w.WriteHeader(500)
return
}
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(200)
w.Write(data)
}
型
请帮帮我谢谢你的好意
预期结果如下
{
"table" : "tablea",
"table_type" : "pubilc"
"field" : [
{
"field" : "name",
"type". : "string",
"detail" : [
{
"domain" : "xxx",
"element" : "jjjjj"
},
{
"domain" : "yyyy",
"element" : "ssss"
}
]
},
{
"field" : "surname",
"type". : "string",
"detail" : [
{
"domain" : "aaaaaa",
"element" : "dddd"
},
{
"domain" : "bbbbbb",
"element" : "eeee"
}
]
}
]
}
型
1条答案
按热度按时间piztneat1#
谢谢@Trock
字符串