将JSON字符串转换为对象 [英] Convert JSON String to Objects
问题描述
我在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
指针: JS中对象的字符串
更新的代码: http://jsfiddle.net/nottinhill/uktLr2g5/
除了纯JavaScript解决方案,我们还与Brennan在 http://jsfiddle.net/nottinhill/uktLr2g5/5 以下解决方案适用于猫鼬存储函数:
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 >
I have such a JSON in JavaScript (Express.js/Mongoose):
// create a document
var demo = new DemoSchema({
hat: { money: "500" },
functions: {
func1: "this.hat.money - (0.02*this.hat.money)"
}
});
Now I want to use this string as objects. Can it be achieved?
e.g.
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)
More Background Info about why to do it this way: https://groups.google.com/forum/#!topic/mongoose-users/lzyjg0b8Vn0
Pointers: String to object in JS
Updated Code: http://jsfiddle.net/nottinhill/uktLr2g5/
In addition to the JavaScript-only solution we worked out with Brennan at http://jsfiddle.net/nottinhill/uktLr2g5/5 the following solution will work for mongoose for storing functions:
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"
});
});
Also see: https://github.com/aheckmann/mongoose-function
这篇关于将JSON字符串转换为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!