【问题标题】:Convert JSON String to Objects将 JSON 字符串转换为对象
【发布时间】:2015-01-03 06:45:36
【问题描述】:

我在 JavaScript (Express.js/Mongoose) 中有这样一个 JSON:

// create a document
var demo = new DemoSchema({
    hat: { money: "500" },
    functions: {
                func1: "this.hat.money - (0.02*this.hat.money)"
               }
});

现在我想将此字符串用作对象。能实现吗?

例如

DemoSchema.virtual('hat.newValue').get(function() {
    return this.functions.func1;
});

console.log('%s is 2% less', demo.hat.newValue); 

// above prints: this.hat.money - (0.02*this.hat.money is 2% less)

更多关于为什么要这样做的背景信息: https://groups.google.com/forum/#!topic/mongoose-users/lzyjg0b8Vn0

指针: String to object in JS

更新代码http://jsfiddle.net/nottinhill/uktLr2g5/

【问题讨论】:

  • 为什么你的函数是字符串而不是函数?我会成功的:func1: function() {this.hat.money - (0.02*this.hat.money) }
  • 有趣,但有两个问题:如何执行该功能以及是否可以在 demo.functions.func1 中更改此类功能?
  • 我不知道 Express 或 Mongoose 是如何工作的,所以我不能确切地告诉你,但你调用它就像你调用任何其他函数一样:console.log('%s is 2% less', demo.hat.newValue()); 而你将无法编辑函数内部的内容,但您始终可以将 func1 重置为新函数。
  • 我明白了。我尝试了这个建议,但即使将其定义为函数,它也会像字符串一样打印到控制台。当使用函数执行括号 ...newValue() 我得到这不是来自 node.js 的函数。
  • 发布您的更新代码

标签: javascript json mongoose


【解决方案1】:

除了我们在http://jsfiddle.net/nottinhill/uktLr2g5/5 与 Brennan 一起制定的纯 JavaScript 解决方案之外,以下解决方案也适用于 mongoose 来存储函数:

var mongoose = require('mongoose')
require('mongoose-function')(mongoose);

var mySchema = mongoose.Schema({ func: Function });
var M = mongoose.model('Functions', mySchema);

var m = new M;
m.func = function(){
  console.log('stored function')
}
m.save(function (err) {
  M.findById(m._id, function (err, doc) {
    doc.func(); // logs "stored function"
  });
});

另见:https://github.com/aheckmann/mongoose-function

【讨论】:

    猜你喜欢
    • 2019-08-27
    • 2020-05-27
    • 1970-01-01
    • 1970-01-01
    • 2011-04-23
    • 2012-06-14
    • 2012-02-20
    • 1970-01-01
    相关资源
    最近更新 更多