douwu3763 2018-08-10 17:58
浏览 123
已采纳

Golang graphql遍历带有子图的地图

Recently I was trying to an implementation of a Mutation Request using GoLang as a Graphql Server, Basically this is the query that i send: As you can see its an array of object that contains name and an array of strings

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

In my Go code I have a type object that is gonna set the values sent

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

and a custom array that is gonna be []Cell

type Cells []*Cell

However when the request is received by GO I get this: Note that this is the print of cellsInterface

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

How can i get each value and assign those in my Array Cells something like this:

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

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

this is my current attempt:

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{}))
}

However this only split the cells array into 0 and 1.

  • 写回答

1条回答 默认 最新

  • douzhan1994 2018-08-11 06:47
    关注

    Range through the map values in the result and append those values to Cell slice. If you are getting an object from json. Then you can unmarshall the bytes into Cell.

    The result when unmarshalling should be a slice of Cell struct 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)
    

    Working Code on Go playground

    Or if you want to use pointers loop over the resolvedCell as

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码