【问题标题】:Golang graphql iterate over map with submapGolang graphql用子图迭代地图
【发布时间】:2018-08-10 17:58:22
【问题描述】:

最近我正在尝试使用 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 中分配这些值 像这样:

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

细胞[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。

【问题讨论】:

  • child 不是一个映射,而是一个整数值切片。你可以遍历它们,从你问的问题中不清楚你到底想要什么。
  • 好吧,我真正想要的是获取在 Mutation 中发送的每个值并将其保存在 Cell 数组中(最后是 Cell 结构类型)
  • 我希望我的评论能更清楚一点@Himanshu
  • 我编辑了这个问题,所以现在它会更清楚
  • 是的,我们可以这样做,只需在您的问题中打印 cellsInterfaceresolvedCells 的输出即可。

标签: arrays json go struct graphql


【解决方案1】:

遍历结果中的映射值并将这些值附加到单元格切片。如果您从 json 获取对象。然后您可以将字节解组到 Cell 中。

解组时的结果应该是Cell结构的一个切片

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

【讨论】:

  • 现在我收到一个错误:不能使用值(类型接口{})作为类型 *附加单元格:需要类型断言
  • @LuisCardozaBird 请检查您需要类型断言以获取基础值的编辑代码
  • 我检查了这个:stackoverflow.com/questions/14289256/… 但他们只考虑一种类型的值(字符串),在这种情况下是字符串和一个数组:/ @Himanshu
  • @LuisCardozaBird 这就是我需要的时间。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-04
  • 2013-01-07
  • 1970-01-01
  • 2014-06-29
  • 2011-10-30
相关资源
最近更新 更多