Travis
Travis

Reputation: 12379

Parse Redis HGETALL object in Node.js

I'm trying to parse an HGETALL object in Node.js.


In Redis CLI:

> HGETALL userList

returns

1) "19578616521094096601"
2) "User 1"
3) "1682930884780137383"
4) "User 2"

In Node:

var redis = require('redis')
,   r = redis.createClient();

console.log(r.HGETALL('userList'));

returns

true

I would like to parse the userList object as JSON or an array but I can't seem to figure out how to pull data out of it.

Upvotes: 6

Views: 20489

Answers (2)

yoyoyojoe
yoyoyojoe

Reputation: 133

Straight from redis.io's own Node.js guide:

await client.hSet('user-session:123', {
    name: 'John',
    surname: 'Smith',
    company: 'Redis',
    age: 29
})

let userSession = await client.hGetAll('user-session:123');
console.log(JSON.stringify(userSession, null, 2));
/*
{
  "surname": "Smith",
  "name": "John",
  "company": "Redis",
  "age": "29"
}
 */

As long as you have the correct collection name / key, your case should be straightforward, and you should get back an object. If you're storing in each property (key) a JSON string (value), don't forget to parse it before using it as an object!

Upvotes: 2

malletjo
malletjo

Reputation: 1786

RedisClient use callback to return the result.

Exemple:

var redis = require('redis'),
    r = redis.createClient();

r.hgetall('userList', function(err, results) {
   if (err) {
       // do something like callback(err) or whatever
   } else {
      // do something with results
      console.log(results)
   }
});

Upvotes: 15

Related Questions