When is this JSON structure getting converted to all strings?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-03 23:35:22

问题


I am sending a JSON structure to my node/express server and saving the object into a database. The problem is that I send JSON with integers and booleans but everything gets saved as strings.

Here is my node/express code:

var express = require('express');

var app = express();
app.enable("jsonp callback");
app.use(express.bodyParser());

// allow cross origin scripting to get data from devices directly
app.all('*', function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
});

app.post('/departures', function(req, res) {

/* I started using this to convert back to integers - but need to solve the problem
    for (var i in req.body.data) {
      req.body.data[i].siteid = parseInt(req.body.data[i].siteid);
    }
*/
    console.log('saving data '+JSON.stringify(req.body.data));
    positionProvider.save(req.body.data, function(){
      res.json({status:'success'});
    })
});

Here is how I am POSTing with jquery:

    var data = [{"siteid":123}];

    $.ajax({
        type: 'POST',
        url: serverUrl + '/departures',
        data: {
            data: data
        },
        success: function(resp) {
            alert('saved departure data '+JSON.stringify(data))
        },
        error: function(err) {
            console.log('error posting to server...');
            console.log(err);
        }
    });

The jquery side reports that it sent {"siteid":123} but the node side reports that it received {"siteid":"123"}.

Where is the integer getting converted to a string?


回答1:


Your data is converted to a string as a product of sending it from client to server. Remember, the client and server are not actually communicating in JSON, they are communicating in text or binary data. The server (Express?) implicitly interprets the data sent as a string, which is converted to JSON if you include the content-type: application/json request header. You'll need explicitly to type check and convert on the server if you want the data to persist in a specific format.

TLDR (comments); don't rely on the client to send valid data. Clean it before you save it to the database.




回答2:


I ran into same problem. jQuery $.post and $.ajax converts integers into strings when stringifying JSON. You can verify it by looking at the data on the server side. Server receives something like { "age": "3" }, while you really want { "age": 3 }.

The solution that works is to avoid giving jQuery pure objects, but give it a string instead:

$.ajax({ type:'POST', url: '/api/...', data: JSON.stringify(data), contentType: 'application/json' })



来源:https://stackoverflow.com/questions/15468640/when-is-this-json-structure-getting-converted-to-all-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!