gpt4 book ai didi

javascript - JSON.Stringify() 强制 int 值 javascript(node.js)

转载 作者:行者123 更新时间:2023-12-03 03:54:00 25 4
gpt4 key购买 nike

大家好,我一直在尝试强制 Json.stringify 的数据为 int,因为在我的 mongodb 上它以字符串形式返回,所以在我的架构上我需要先这样做

var UserSchema = mongoose.Schema({
username:{
type: String,
index:true
},
influenceid:{
type:String
},
question:{
type:String
},
amount:{
type:String //i need this to be a type:Number instead of string
}
});

在我的 dialog.js 上,我将 json 数据放入其中

 socket.emit('dollar quest', JSON.stringify(result[0]), 
JSON.stringify(result[1]), inUserId, myuserid, 'dquest');

在我的服务器上,我获取这样的数据并将其扔到我的 mongodb

socket.on('dollar quest', function(dolquest,dolamnt,uid,stud,stat){
var info = new InfoUser({
username: stud,
amount: dolamnt,
question: dolquest
});

InfoUser.createUser(info,function(err,user){
if(err)throw err;
console.log(user);
});
});

但是我的 mlab 上的输出是这样的

"username": "stsam1",

"amount": "\"12500\"",

"question": "\"how are you\"",

我如何将我的金额转换为 type:Number 以便它像这样返回到我的 mlab

"amount": 12500,

最佳答案

您可以提供 replacer functionJSON.stringify ,当键名称为 "amount" 时,它将把值转换为数字:

function theReplacer(key, value) {
return key === "amount" ? +value : value;
}

然后

var json = JSON.stringify(yourObject, theReplacer);

function theReplacer(key, value) {
return key === "amount" ? +value : value;
}
var object = {
username: "a",
influenceid: "b",
question: "c",
amount: "42"
};
var json = JSON.stringify(object, theReplacer, 2);
console.log(json);

该示例会将任何“amount”字段的值转换为数字,但如果您需要限制它,您可以对其进行优化。

关于javascript - JSON.Stringify() 强制 int 值 javascript(node.js),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45034683/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com