How to "push" a json object to an array in Go?

huangapple go评论80阅读模式
英文:

How to "push" a json object to an array in Go?

问题

我只会为你提供翻译服务,以下是你要翻译的内容:

我只是从 Redis 数据库中获取 JSON,并尝试将其添加到一个数组中。

在 JavaScript 中,我会这样做:

var myarray = [];

//blah blah 联系 Redis 并获取响应

myarray.push(redisresponse);

我在 Go 语言中不太清楚如何做到这一点。

欢迎提供库的建议!

英文:

I'm just fetching json from a Redis db and trying to append it to an array.

In Javascript I would do something like this:

var myarray = [];

//blah blah contact Redis and get the response

myarray.push(redisresponse);

I'm having trouble figuring out how to do that in Go.

Library suggestions welcome!

答案1

得分: 2

假设你想从Redis获取一个字符串响应。使用redigo库,你可以发送一个命令并使用其辅助方法接收响应。

以下是如何实现的代码片段:

import "github.com/garyburd/redigo/redis"

someCap := 10 // 根据需要设置切片的大小。
myarray := make([]string, someCap)
redisConn, err := redis.Dial("tcp", "your_redis_host:port")
if err != nil {
    // 根据需要处理错误。
}
defer redisConn.Close()

resp, err := redis.String(redisConn.Do("GET", "some_key"))
if err != nil {
    // 根据需要处理错误。
}
myarray = append(myarray, resp)

以上代码使用redigo库连接到Redis,并发送一个"GET"命令来获取键为"some_key"的值,并将其存储在变量resp中。然后,将resp添加到myarray切片中。

英文:

Let's say you want to get a string response from Redis. Using the redigo library you can send a command and receive the response back using it's helper methods.

This is a snippet of how you can do that:

import "github.com/garyburd/redigo/redis"

someCap := 10 // Make the slice however large you need it.
myarray := make([]string, someCap)
redisConn, err := redis.Dial("tcp" "your_redis_host:port")
if err != nil {
    // Handle your error accordingly.
}
defer redisConn.Close()

resp, err := redis.String(redisConn.Do("GET", "some_key"))
if err != nil {
    // Handle your error accordingly.
}
myarray = append(myarray, resp)

huangapple
  • 本文由 发表于 2017年3月1日 07:19:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/42520555.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定