[英]When implementing redis with node, how do you add multiple json object to Hmset or hset or any data type?
例如->
var redis = require('redis');
var port=6379;
var host="127.0.0.1";
var redisClient=null;
redisClient = redis.createClient(port, host);
redisClient.on('connect',function(err,reply){
if(err)
{
console.log("Erro with connectivity");
}
else
{
console.log("connected with redis");
}
});
数据变量是多个json对象
redisClient.hset('users',data);
redisClient.hgetall('users',function(err,object){
if(err)
{
console.log("Getting Hmset Error");
}
else
{
console.log("----Retrieving HMSET--");
console.log(object);
console.log("---End Retriving HMSET");
}
});
但是json并不是完美的方式。
给出这样的结果。
data= { javascript: 'AngularJS',
css: 'Bootstrap',
users: '[object Object]',
node: 'Express',
'[object Object]': '[object Object]' }
序列化之前的数据。 例如redisClient.hset ('users', JSON.stringify (data));
Redis使用字符串,您需要将JSON(实际上是一个JavaScript对象)转换为JSON字符串:
redisClient.hset('users', JSON.stringify(data));
然后,当您提取JSON字符串时,必须将其解析回JavaScript对象:
redisClient.hget('users', function (err, str) {
if (err) return console.error(err);
var data = JSON.parse(str); // note this might throw an exception
});
需要注意的一件事是,您没有将回调传递到hset方法中,这意味着不能保证在调用hget时它已完成。 您也应该考虑解决该问题。
Redis使用此数据类型来操作JSON,您必须将其转换为字符串
redisClient.hset('users', JSON.stringify(data));
strings — a sequence of binary safe bytes up to 512 MB.
hashes — a collection of key value pairs.
lists — an in-insertion-order collection of strings.
sets — a collection of unique strings with no ordering.
sorted sets — a collection
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.