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

时间:2017-07-11 12:29:07

标签: javascript json node.js mongodb

大家好我每天都试图强迫我的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上的输出就像这样

  

“用户名”:“stsam1”,

     

“金额”:“\”12500 \“”,

     

“问题”:“\”你好吗

如何将我的金额转换为类型:数字,以便它会像我一样在我的mlab上返回

  

“金额”:12500,

3 个答案:

答案 0 :(得分:1)

您可以提供replacer functionfunction 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"时,该值会将值转换为数字:

 webView = (WebView) findViewById(R.id.career_view);
            URL = "http://test.dk/";
            webView.getSettings().setJavaScriptEnabled(true);
            webView.loadUrl(URL); // Specify the URL to load when the application starts
            webView.setWebChromeClient(new WebChromeClient(){
                public void onProgressChanged(WebView view, int progress)
                {
                    //Make the bar disappear after URL is loaded, and changes string to Loading...
                    setTitle("Loading...");
                    setProgress(progress * 100); //Make the bar disappear after URL is loaded
                    // Return the app name after finish loading
                    if(progress == 70)
                        setTitle(R.string.app_name);
                }
            });
            webView.setWebViewClient(new SSLTolerentWebViewClient());
            webView.getSettings().setLoadsImagesAutomatically(true);
            webView.getSettings().setAllowFileAccess(true);
            webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
            webView.setInitialScale(1); // Set the initial zoom scale
            webView.getSettings().setBuiltInZoomControls(true); // Initialize zoom controls for your WebView component
            webView.getSettings().setUseWideViewPort(true);

然后

private class SSLTolerentWebViewClient extends WebViewClient {
        public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {

            AlertDialog.Builder builder = new AlertDialog.Builder(Activities.this);
            AlertDialog alertDialog = builder.create();
            String message = "SSL Certificate error.";
            switch (error.getPrimaryError()) {
                case SslError.SSL_UNTRUSTED:
                    message = "The certificate authority is not trusted.";
                    break;
                case SslError.SSL_EXPIRED:
                    message = "The certificate has expired.";
                    break;
                case SslError.SSL_IDMISMATCH:
                    message = "The certificate Hostname mismatch.";
                    break;
                case SslError.SSL_NOTYETVALID:
                    message = "The certificate is not yet valid.";
                    break;
            }

            message += " Do you want to continue anyway?";
            alertDialog.setTitle("SSL Certificate Error");
            alertDialog.setMessage(message);
            alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // Ignore SSL certificate errors
                    handler.proceed();
                }
            });

            alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    handler.cancel();
                }
            });
            alertDialog.show();
        }
    }

case

该示例会将任意 select * from products p, product_languages l where p.prd_id = l.prd_id order by (case language_id when 2 then 1 when 1 then 2 when 4 then 3 end) asc 字段的值转换为数字,但如果您需要对其进行限制,则可以对其进行优化。

答案 1 :(得分:0)

您可以将金额字段设为Number,然后它会自动从字符串

转换为数字
amount:{
   type: Number
}

或者您可以使用parse.float之类的

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

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

答案 2 :(得分:0)

我挖了这个,它对我有用,所以我会回答我自己的问题,但谢谢你的帮助先生T.J和Shaib。这就是我的所作所为。

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

并添加了

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

所以这个想法正在取代,所以TJ爵士有正确的想法