Parse Redis HGETALL object in Node.js
Asked Answered
A

2

6

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.

Aksel answered 10/11, 2011 at 21:20 Comment(0)
F
15

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)
   }
});
Figureground answered 10/11, 2011 at 22:8 Comment(4)
Thanks racar. Using the code above I was then able to loop through the object properties using for (var userID in results) {}.Aksel
note that for key in object is not generally the best approach. Better to use Object.keys(object).forEach(key => {...});Tarpley
why is for..in "not generally the best approach"...? I'm fairly sure its faster, and it lets you break early.Toodleoo
I just came across this answer searching stuff about hgetall, and saw this comment. Beware that with for..in you iterate over inherited enumerable properties too, and you might not want that. Check #25053258Igenia
E
2

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!

Equities answered 14/12, 2023 at 2:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.