Ben
Ben

Reputation: 6086

Node.js, Express, jQuery.param() - Remove quotes from JSON

I am serializing a JSON object on the client using jQuery.param():

var test = {"coordinates":[[-122.610168,37.598167],[-122.288818,37.598167],[-122.288818,37.845833],[-122.610168,37.845833],[-122.610168,37.598167]]};

console.log($.param( test ));

After making a GET request, on the server side within an Express route, I access the object with:

console.log('Server received: ' + JSON.stringify(req.query.coordinates));

This outputs the below - note the quotes around each coordinate:

Server received: [["-122.610168","37.598167"],["-122.288818","37.598167"],["-122.288818","37.845833"],["-122.610168","37.845833"],["-122.610168","37.598167"]]

How can I remove the quotes? I can parse to a string and use a regex then parse back to JSON, but that seems inefficient. Can anyone advise what part of the process is adding them and how they can be removed?

Upvotes: 1

Views: 612

Answers (2)

sgress454
sgress454

Reputation: 24948

Something tells me there's a way to do this in a single, chained function call by using bind, but the best I could come up with was:

var coords = data.map(function(arr){return arr.map(parseFloat);})

This has the benefit of being non-destructive (the original data variable remains intact).

Upvotes: 0

Mritunjay
Mritunjay

Reputation: 25892

Just try like bellow

var data = [["-122.610168","37.598167"],["-122.288818","37.598167"],["-122.288818","37.845833"],["-122.610168","37.845833"],["-122.610168","37.598167"]]

data.forEach(function(arr){
   arr[0] = +arr[0];
   arr[1] = +arr[1];
})

console.log(data)// prints[[-122.610168,37.598167],[-122.288818,37.598167],[-122.288818,37.845833],[-122.610168,37.845833],[-122.610168,37.598167]]

Upvotes: 1

Related Questions