Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is this JSON structure getting converted to all strings?

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?

like image 499
Joe Beuckman Avatar asked Mar 18 '13 01:03

Joe Beuckman


2 Answers

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.

like image 52
cjohn Avatar answered Oct 07 '22 18:10

cjohn


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' })

like image 41
yvoronen Avatar answered Oct 07 '22 18:10

yvoronen