gpt4 book ai didi

arrays - Golang graphql 使用子图迭代 map

转载 作者:IT王子 更新时间:2023-10-29 02:09:23 25 4
gpt4 key购买 nike

最近我正在尝试使用 GoLang 作为 Graphql 服务器来实现一个 Mutation Request,基本上这是我发送的查询:正如你所看到的,它是一个对象数组,其中包含 name 和一个字符串数组

mutation{
CellTest(cells:[{name:"lero",child:["1","2"]},{name:"lero2",child:["12","22"]}]){
querybody
}
}

在我的 Go 代码中,我有一个类型对象,它将设置发送的值

type Cell struct {
name string `json:"name"`
child []string `json:"child"`
}

和一个将成为 []Cell

的自定义数组
type Cells []*Cell

然而,当 GO 收到请求时,我得到了这个:请注意,这是 cellsInterface

的打印

[map[child:[1 2] name:lero] map[child:[12 22] name:lero2]]

如何获取每个值并将它们分配到我的Array Cells像这样:

Cells[0] = {name="first",child={"1","2"}}

Cells[1] = {name="second",child={"hello","good"}}

这是我目前的尝试:

var resolvedCells Cells
cellsInterface := params.Args["cells"].([]interface{})
cellsByte, err := json.Marshal(cellsInterface)
if err != nil {
fmt.Println("marshal the input json", err)
return resolvedCells, err
}

if err := json.Unmarshal(cellsByte, &resolvedCells); err != nil {
fmt.Println("unmarshal the input json to Data.Cells", err)
return resolvedCells, err
}

for cell := range resolvedCells {
fmt.Println(cellsInterface[cell].([]interface{}))
}

然而,这只是将元胞数组拆分为 0 和 1。

最佳答案

遍历结果中的 map 值并将这些值附加到 Cell slice 。如果你从 json 中获取一个对象。然后您可以将字节解码到 Cell 中。

解码时的结果应该是一片 Cell 结构 as

var resolvedCells []Cell
if err := json.Unmarshal(cellsByte, &resolvedCells); err != nil {
fmt.Println("unmarshal the input json to Data.Cells", err)
}
fmt.Println(resolvedCells)

关于 Go playground 的工作代码

或者如果你想在 resolvedCell 上使用指针循环作为

type Cells []*Cell

func main() {
var resolvedCells Cells
if err := json.Unmarshal(cellsByte, &resolvedCells); err != nil {
fmt.Println("unmarshal the input json to Data.Cells", err)
}
fmt.Println(*resolvedCells[1])
for _, value := range resolvedCells{
fmt.Println(value)
fmt.Printf("%+v",value.Child) // access child struct value of array
}
}

Playground example

关于arrays - Golang graphql 使用子图迭代 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51791799/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com