1

Hi I am trying to store a JSON in redis using ioredis. This JSON comprises of one function too. The structure of my json is something like:

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';
    }
  }
}

I am using IOredis to store this json in 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});
      }
    });
  }
});

When I am doing this the determineConfig key is truncated from the object as JSON.stringify removes it if the type is function. Is there some way I can store this function in redis and excute that once I get the data back from redis. I do not want to store the function as a string and then use eval or new Function to evaluate.

4

1 回答 1

2

JSON 是一种将任意数据对象编码为字符串的方法,这些字符串可以在以后解析回其原始对象。因此,JSON 仅编码“简单”数据类型:nulltruefalseNumber和.ArrayObject

JSON 不支持任何具有专用内部表示的数据类型,例如 Date、Stream 或 Buffer。

要查看此操作,请尝试

 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()非常危险,因此已被弃用。

于 2019-01-14T20:12:04.410 回答