LilRazi
LilRazi

Reputation: 770

converting string to json with date object on string

I am trying to convert the string to json object but every time I tried I am getting error. Below is the my string format. All I did is passed the below string format to JSON.parse function but it did not work. If I passed the real string like "1/1/2014" instead of date object it works perfectly fine. What should I do to make this json conversion safely.

"[{ \"ID\": 0, \"ApplyDate\": new Date(2011, 0, 3, 0, 0, 0, 0),
\"Phy\":37.74,\"Eng\": 40, \"Chem\": 37.62, \"math\": 39.17 },{ \"ID\": 1,
\"ApplyDate\": new Date(2010, 11, 1, 0, 0, 0, 0), \"Phy\": 37.15, \"Eng\":
37.99, \"Chem\": 36.51, \"math\": 37.51 }]";

Upvotes: 0

Views: 259

Answers (3)

davidkonrad
davidkonrad

Reputation: 85528

As it is I dont think there is any other way around than eval(). The main problem is, that the sourcestring not is valid JSON but a literal-like structure that has been through some kind of escaping as string.

So remove the escapes first, s is the string from OP :

s = s.replace("\\", "");

convert it (back?) to literal with eval() :

var literal = eval(s);

now the Date objects inside the created literal actually works :

console.log(literal[0].ApplyDate.getFullYear());

outputs 2011

demo -> http://jsfiddle.net/hv7ar3qr/


Now you can turn literal back to a valid JSON string with

var json = JSON.stringify(literal);

json will look like this :

[
    {
        "ID": 0,
        "ApplyDate": "2011-01-02T23:00:00.000Z",
        "Phy": 37.74,
        "Eng": 40,
        "Chem": 37.62,
        "math": 39.17
    },
    {
        "ID": 1,
        "ApplyDate": "2010-11-30T23:00:00.000Z",
        "Phy": 37.15,
        "Eng": 37.99,
        "Chem": 36.51,
        "math": 37.51
    }
]

JSON.parse(json) can be used to turn json into an iterable JSON object. A long way to go, where first step needs to be eval().

Upvotes: 1

Hitmands
Hitmands

Reputation: 14179

This isn't JSON, so, JSON.parse cannot help you...

By the way:

  1. the ID of the first object isn't escaped,
  2. new Date(bla bla bla) isn't JSON, at least you should pass something like that "new Date(2011, 0, 3, 0, 0, 0, 0)"

The best way to get a date is encoding it as a string...

(new Date()).toString();

if you are in love with your code, try to wrap the date object as a string and then exec an eval...

var a = eval("new Date()")

Upvotes: 1

steo
steo

Reputation: 4656

You should first convert Date to String then encode your json

new Date().toString(); //"Fri Nov 06 2015 19:37:51 GMT+0100"

You can change the format of Date with

var date = new Date();
date.format() //the format

Here a method to get a yyyymmdd format

So if you have the object

var object = { date: theDate };
object.date = object.date.toString();
var json = JSON.stringify(object.date);

Upvotes: 0

Related Questions