erythraios
erythraios

Reputation: 339

JSON posting operation converts object values to string type

I have an object containing a date object. When I post it to a NodeJS server, it's still an object but the time has been converted to a string. Is there any way to avoid this? I can't parse the entire object because I get an "Unexpected token o" error (I assume because it's still an object).

Before:

Object {title: " - fd", start: Tue Feb 11 2014 09:00:00 GMT-0500 (EST), end: Tue Feb 11 2014 10:00:00 GMT-0500 (EST), allDay: false, id: ""…}

After:

Object
allDay: "false"
end: "Tue Feb 11 2014 10:00:00 GMT-0500 (EST)"
id: ""
room: "Shower 1"
start: "Tue Feb 11 2014 09:00:00 GMT-0500 (EST)"
title: " - fd"

Upvotes: 0

Views: 62

Answers (1)

Tobias
Tobias

Reputation: 7771

You cannot include Date objects in JSON. You can convert them to a number and back to a date on the server:

// Convert Date to number on client side
objToSend.foo.myDate = objToSend.foo.myDate.getTime();

// Convert number to date on server side
objReceived.foo.myDate = new Date(+objReceived.foo.myDate);

That requires your application to know which properties are dates and which are not.

Upvotes: 1

Related Questions