简体   繁体   English

如何将带有Date的String转换为Json对象?

[英]How to convert String with Date to Json Object?

I want to convert one string to JSON Object in my Javascript. 我想在我的Javascript中将一个字符串转换为JSON对象。 When I convert to Json Object the date in the String totally changed 当我转换为Json对象时,String中的日期完全改变了

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 我将使用以下内容转换为JSON对象

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? 在我的javascript中的某个地方。所以我认为它是因为日期在Json对象中没有正确转换..它是如此??可以有人请指导吗?

Don't use eval() 不要使用eval()

Use JSON.parse() to convert the string into a json object. 使用JSON.parse()将字符串转换为json对象。 Plus as your JsonData isn't valid JSON, use JSON.stringify() also. 另外,由于您的JsonData无效JSON,也请使用JSON.stringify()

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));
<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). 然后我得到的结果是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. 我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM