【问题标题】:Symbol to string with JSON.stringify使用 JSON.stringify 字符串化的符号
【发布时间】:2019-12-01 08:04:01
【问题描述】:

为了在 Redis 中创建唯一键,我需要将 Symbol 转换为字符串,但我不能。

我已经尝试过使用 Object.toString(obj) 和 String(obj) 但我得到错误或 [Object] 结果…。

这是控制器

const name = req.params.name;
let obj;
obj.data.name = {
          [Op.like]: '%' + name + '%'
        };
}

这是我使用 stringify 的 redis 控制器。我使用 obj 作为参数。

const hashed = crypto.createHmac('sha256', secretHashKey)
          .update(JSON.stringify(obj))
          .digest('hex');

我希望输出基于我的参数“obj”,但现在它没有得到它,所以我无法为不同的值创建唯一键。

【问题讨论】:

    标签: node.js redis sequelize.js stringify


    【解决方案1】:

    如果您的意思是these Symbols,则不能将它们转换为字符串。

    它们被创建为独一无二且“不可逆转”,因此您也可以使用它们来保持更“安全”的各种属性或方法。示例:

    const a = Symbol('a')
    
    class Foobar {
      constructor (_a) {
        this[a] = _a
      }
    }
    
    const foobar = new Foobar('aaa')
    console.log(foobar) // output: Foobar { [Symbol(a)]: 'aaa' }
    
    const fake = Symbol('a')
    foobar[fake] = 'fake'
    console.log(foobar) // output: Foobar { [Symbol(a)]: 'aaa', [Symbol(a)]: 'fake' }
    

    你不能破坏原来的,除非你有原来的符号。

    另一个例子(info about the JSON.stringify here):

    const a = Symbol('a')
    
    const foobar = {}
    foobar[a] = 'aaa'
    
    console.log(foobar) // output: { [Symbol(a)]: 'aaa' }
    console.log(JSON.stringify(foobar)) // output: {} 
    
    const fake = Symbol('a')
    foobar[fake] = 'fake'
    console.log(foobar) // output: { [Symbol(a)]: 'aaa', [Symbol(a)]: 'fake' }
    

    希望这些信息对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-04
      • 2013-08-25
      • 1970-01-01
      • 1970-01-01
      • 2015-12-20
      • 1970-01-01
      相关资源
      最近更新 更多