gpt4 book ai didi

javascript - 将字符串转换为 JSON

转载 作者:可可西里 更新时间:2023-11-01 11:22:43 25 4
gpt4 key购买 nike

我是 javascript 的新手,我正在尝试将 redis-cli INFO 命令输出转换为 JSON。我试图转换为 JSON 的字符串是这样的

    "redis_version:2.4.8\r\nredis_git_sha1:b85ba5fb\r\nredis_git_dirty:0\r\narch_bits:64\r\nmultiplexing_api:kqueue\r\ngcc_version:4.2.1\r\nprocess_id:6403\r\nuptime_in_seconds:963411\r\nuptime_in_days:11\r\nlru_clock:815387\r\nused_cpu_sys:67.32\r\nused_cpu_user:91.89\r\nused_cpu_sys_children:42.23\r\nused_cpu_user_children:132.57\r\nconnected_clients:2\r\nconnected_slaves:1\r\nclient_longest_output_list:0\r\nclient_biggest_input_buf:0\r\nblocked_clients:0\r\nused_memory:162549360\r\nused_memory_human:155.02M\r\nused_memory_rss:147972096\r\nused_memory_peak:191943360\r\nused_memory_peak_human:183.05M\r\nmem_fragmentation_ratio:0.91\r\nmem_allocator:libc\r\nloading:0\r\naof_enabled:1\r\nchanges_since_last_save:1\r\nbgsave_in_progress:1\r\nlast_save_time:1350325258\r\nbgrewriteaof_in_progress:0\r\ntotal_connections_received:187\r\ntotal_commands_processed:269264\r\nexpired_keys:180\r\nevicted_keys:0\r\nkeyspace_hits:202518\r\nkeyspace_misses:11675\r\npubsub_channels:0\r\npubsub_patterns:0\r\nlatest_fork_usec:2198\r\nvm_enabled:0\r\nrole:master\r\naof_current_size:159904546\r\naof_base_size:158667118\r\naof_pending_rewrite:0\r\naof_buffer_length:0\r\naof_pending_bio_fsync:0\r\nslave0:127.0.0.1,62716,online\r\ndb0:keys=356937,expires=0\r\n"

非常感谢任何关于如何将其转换为 JSON 对象的指示。谢谢!

最佳答案

你可以像这样简单地做一些事情:

​var fields = str.split('\r\n'), result = {};
for(var i = 0, len = fields.length; i < len; ++i) {
var props = fields[i].split(':');
if(props.length === 2) {
result[props[0]] = props[1];
}
}

console.log(result);​​​​
console.log(JSON.stringify(result));

我在 http://jsfiddle.net/uHtT3/1/ 创建了一个 jsfiddle .

关于javascript - 将字符串转换为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12907909/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com