1

redis INFO 逗号返回字符串,如redis_version:2.2.14\r\nredis_git_sha1:00000000\r\nredis_git_dirty:0\r\narch_bits:32

如何转换字符串以获取类似的 JSON 对象

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

4 回答 4

7

我不知道你为什么要这样做,但这里有一个简单的例子:

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;
}
于 2012-10-16T07:59:58.350 回答
3

您可以使用node-redis-info

npm install redis-info

用法:

> 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' ] ]
于 2013-11-05T09:49:38.953 回答
1

简单的:

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

对于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))
于 2020-12-02T11:58:46.940 回答
0
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;
};

资源

于 2020-04-10T04:06:27.217 回答