社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Redis

使用nodejs在json redis中设置函数类型

Shubham Jain • 7 年前 • 2336 次点击  

嗨,我正在尝试使用ioredis在redis中存储JSON。这个JSON也包含一个函数。我的JSON的结构如下:

var object = {
  site1: {
    active: true,
    config1:{
      // Some config in JSON format
    },
    config2: {
      // Some other config in JSON format
    },
    determineConfig: function(condition){
      if(condition) {
        return 'config1';
      }
      return 'config2';
    }
  }
}

我正在使用ioredis将此JSON存储在redis中:

redisClient.set(PLUGIN_CONFIG_REDIS_KEY, pluginData.pluginData, function (err, response) {
  if (!err) {
    redisClient.set("somekey", JSON.stringify(object), function (err, response) {
      if (!err) {
        res.json({message: response});
      }
    });
  }
});

当我这样做的时候 determineConfig 从中截断键 object 作为 JSON.stringify 如果类型为“函数”,则将其移除。有什么方法可以把这个函数存储在redis中,一旦我从redis中得到数据,就可以执行这个操作吗?我不想将函数存储为字符串,然后使用 eval 或 new Function 评估。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/30843
文章 [ 1 ]  |  最新文章 7 年前
Rob Raisch
Reply   •   1 楼
Rob Raisch    7 年前

JSON是一种将任意数据对象编码为字符串的方法,这些字符串可以在以后的某个时间解析回其原始对象。因此,JSON只对“简单”数据类型进行编码: null , true , false , Number , Array 和 Object .

JSON不支持任何具有专门的内部表示形式(如日期、流或缓冲区)的数据类型。

要看到这一点,请尝试

 typeof JSON.parse(JSON.stringify(new Date)) // => string

因为它们的底层二进制表示不能编码到字符串中,所以JSON不支持函数的编码。

JSON.stringify({ f: () => {} }) // => {}

虽然您表示不希望这样做,但实现目标的唯一方法是将函数序列化为其源代码(由字符串表示),如:

const determineConfig = function(condition){
  if(condition) {
    return 'config1';
  }
  return 'config2';
}

{
  determineConfig: determineConfig.toString()
}

而且 exec 或者在接收端重新实例化函数。

我建议不要这样做,因为 exec() 非常危险,因此被弃用。