user1386776
user1386776

Reputation: 395

Converting redis INFO command response string to JSON object in nodejs

The redis INFO commad returns the string like redis_version:2.2.14\r\nredis_git_sha1:00000000\r\nredis_git_dirty:0\r\narch_bits:32

How can I convert the string to get a JSON object something like

 { 
     "redis_version":"x",
     "key2":"value"
 }

Upvotes: 1

Views: 3645

Answers (4)

valiy vvv
valiy vvv

Reputation: 11

Simple:

#!/usr/bin/env python
import redis
import json
print(json.dumps(redis.Redis().info()))

For zabbix Template DB Redis:

#!/usr/bin/env python
import redis
import json
import sys
r = redis.Redis.from_url(sys.argv[1])
a = {}
sections = ["CPU","Clients","Cluster","Keyspace","Memory","Modules","Persistence","Replication","Server","Stats"]
for section in sections:
    a[section]=r.info(section)
print(json.dumps(a))

Upvotes: 1

PaulMest
PaulMest

Reputation: 14985

interface RedisInfo {
  [key: string]: any;
}

/**
 * This was taken from how `.serverInfo` was parsed in the ioredis library
 * https://github.com/luin/ioredis/blob/f275bc24de3825f80415a69ff227a45251dd1a3b/lib/redis/index.ts#L500
 * @param infoString Result of Redis INFO command
 */
const parseRedisInfo = (infoString: string): RedisInfo => {
  const info: RedisInfo = {};

  const lines = infoString.split('\r\n');
  for (let i = 0; i < lines.length; ++i) {
    const parts = lines[i].split(':');
    if (parts[1]) {
      info[parts[0]] = parts[1];
    }
  }
  return info;
};

Source

Upvotes: 0

FGRibreau
FGRibreau

Reputation: 7239

You can use node-redis-info:

npm install redis-info

Usage:

> var parser = require('redis-info');
undefined
> var info = parser.parse(redis_info_str);
undefined
> info.fields.redis_version
2.6.1
> info.startWith('pubsub')
[ [ 'pubsub_channels', '2' ],
  [ 'pubsub_patterns', '0' ] ]
> info.contains('memory')
[ [ 'used_memory', '15080416' ],
  [ 'used_memory_human', '14.38M' ],
  [ 'used_memory_rss', '21258240' ],
  [ 'used_memory_peak', '18985904' ],
  [ 'used_memory_peak_human', '18.11M' ] ]

Upvotes: 3

freakish
freakish

Reputation: 56467

I don't know why would you want to do that, but here's a simple example:

function parseInfo( info ) {
    var lines = info.split( "\r\n" );
    var obj = { };
    for ( var i = 0, l = info.length; i < l; i++ ) {
        var line = lines[ i ];
        if ( line && line.split ) {
            line = line.split( ":" );
            if ( line.length > 1 ) {
                var key = line.shift( );
                obj[ key ] = line.join( ":" );
            }
        }
    }
    return obj;
}

Upvotes: 7

Related Questions