arrays - Golang graphql 使用子图迭代 map

标签 arrays json go struct graphql

最近我正在尝试使用 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/

相关文章:

google-app-engine - 数据存储持久化是其中之一

java - 读取 csv 文件并将其值存储在二维 int 数组中 (java)

c - 仅使用返回的指针获取 malloc 的大小

javascript - 在 JavaScript 中,如何编写一个函数来接收命名元素以有条件地插入数组?

java - 如何使用retrofit解析json数组?

javascript json 不显示所有条目

Php Preg_Match 获取数组中的引用字符串

javascript - 如何用 JSON 的返回值填充 FIXED 表的特定位置?

google-app-engine - AppEngine "appengine"包始终失败,出现 "syscall"或 "unsafe"导入失败

go - 使用具有 OOP 风格的 fyne 小部件