广告
返回顶部
首页 > 资讯 > 后端开发 > GO >Golang graphql 使用子图迭代地图
  • 515
分享到

Golang graphql 使用子图迭代地图

2024-04-05 00:04:00 515人浏览 安东尼
摘要

大家好,我们又见面了啊~本文《golang graphql 使用子图迭代地图》的内容中将会涉及到等等。如果你正在学习Golang相关知识,欢迎关注我,以后会给大家带来更多Golang相关文章,希望我

大家好,我们又见面了啊~本文《golang graphql 使用子图迭代地图》的内容中将会涉及到等等。如果你正在学习Golang相关知识,欢迎关注我,以后会给大家带来更多Golang相关文章,希望我们能一起进步!下面就开始本文的正式内容~

问题内容

最近我尝试使用 golang 作为 graphql 服务器来实现突变请求,基本上这是我发送的查询:如您所见,它是一个对象数组,其中包含 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

的打印内容

[地图[子项:[1 2] 名称:lero] 地图[子项:[12 22] 名称:lero2]]

如何获取每个值并将其分配到我的数组单元中 像这样的东西:

单元格[0] = {name="first",child={"1","2"}} 细胞[1] = {name =“第二”,child = {“你好”,“好”}}

这是我当前的尝试:

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。


解决方案


对结果中的地图值进行范围划分,并将这些值附加到单元格切片中。如果你从 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

到这里,我们也就讲完了《Golang graphql 使用子图迭代地图》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注编程网公众号,带你了解更多关于的知识点!

您可能感兴趣的文档:

--结束END--

本文标题: Golang graphql 使用子图迭代地图

本文链接: https://www.lsjlt.com/news/596750.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作