1

I want to convert one string to JSON Object in my Javascript. When I convert to Json Object the date in the String totally changed

This is my string

var JsonData=[[2013-02-27,787],[2013-02-26,131],[2013-02-02,0],[2013-01-20,8],[2012-12-28,12]]

I am converting to JSON object with the following

var json = eval( JsonData );

Then I get following result in alert

1984,787,1985,131,2009,0,1992,8,1972,12

Can anyone please guide me? How do I solve this?

Now I Got error of following

Timestamp: 3/7/2013 1:10:36 PM
Error: TypeError: this.proxy.getTime is not a function

in somewhere in my javascript..so i am thinking that its beacuse the date is not converted properly in Json Object..is it so??can anyone please guide?

BhavikKama
  • 8,566
  • 12
  • 94
  • 164
  • 1
    wow I've noticed the data conversion performed arithmetic operations :) 2013-02-27 = 1984. 2013-02-26 = 1985. Just a guess but maybe you should enclose them in quotes. :) – Oneb Mar 07 '13 at 07:24
  • ok.i had got same string in json object to..but its now not working ahead..because i want it as date object in json ..so can you please tell me how to do that – BhavikKama Mar 07 '13 at 07:29

2 Answers2

3

Don't use eval()

Use JSON.parse() to convert the string into a json object. Plus as your JsonData isn't valid JSON, use JSON.stringify() also.

var JsonData = [[2013-02-27,787],[2013-02-26,131],[2013-02-02,0],[2013-01-20,8],[2012-12-28,12]];
JSONObject = JSON.parse(JSON.stringify(JsonData));
Siddharth Gupta
  • 897
  • 5
  • 20
1
<script>
var JsonData=[[2013-02-27,787],[2013-02-26,131],[2013-02-02,0],[2013-01-20,8],["2012-12-28,12"],["Fri May 04 2012 01:17:07 GMT-0700 (PDT)"]]
var json = eval( JsonData );
alert(json);
</script>

Then the result I got is 1984,787,1985,131,2009,0,1992,8,2012-12-28,12,Fri May 04 2012 01:17:07 GMT-0700 (PDT). So I think the the dates should be enclosed in double quotes. I hope this helps.

Hari
  • 310
  • 3
  • 14
  • yes i got solved that problem...but its now not working ahead..because i want it as date object in json ..so can you please tell me how to do that – BhavikKama Mar 07 '13 at 07:33
  • I think you might need to serialize the date before sending as json. Can you please take a look at this post also, it may help you.[See this post](http://stackoverflow.com/questions/4511705/how-to-parse-json-to-receive-a-date-object-in-javascript). I saw in many case data is send like that. Also I'm not sure about json's date side. – Hari Mar 07 '13 at 09:00