admin管理员组

文章数量:1306029

I am using flot to do some graphing and I am having some trouble passing the tickSize with my json. I am using MVC and pass the json in a model. Here is some code to grab the json within my javascript function:

var json = '<%=Model.Json %>';
var data = jQuery.parseJSON(json);

Here is how the Json looks leaving the controller:

{\"GraphData\":[{\"X\":1333929600000,\"Y\":0.0},{\"X\":1333670400000,\"Y\":0.46}],\"Max\":1333324800000,\"Min\":1333929600000,\"TickSize\":\"[1, 'day']\"}

The part that I am having trouble with is "TickSize." As you can see, "[1, 'day']" has the square brackets. I think there is some parsing problem because [] usually means an array. Flot wants the tick size in this format. How do I construct my Json so I can grab the TickSize?

I am using flot to do some graphing and I am having some trouble passing the tickSize with my json. I am using MVC and pass the json in a model. Here is some code to grab the json within my javascript function:

var json = '<%=Model.Json %>';
var data = jQuery.parseJSON(json);

Here is how the Json looks leaving the controller:

{\"GraphData\":[{\"X\":1333929600000,\"Y\":0.0},{\"X\":1333670400000,\"Y\":0.46}],\"Max\":1333324800000,\"Min\":1333929600000,\"TickSize\":\"[1, 'day']\"}

The part that I am having trouble with is "TickSize." As you can see, "[1, 'day']" has the square brackets. I think there is some parsing problem because [] usually means an array. Flot wants the tick size in this format. How do I construct my Json so I can grab the TickSize?

Share Improve this question asked Apr 9, 2012 at 21:35 aelstonjonesaelstonjones 3822 gold badges9 silver badges25 bronze badges 1
  • I think TickSize is considered a string and not array in JSON because it is quoted. If it wasn't quoted it would be an array. – stevebot Commented Apr 9, 2012 at 21:40
Add a ment  | 

3 Answers 3

Reset to default 2

The issue is the single-quotes in the string value, since you're trying to wrap the JSON string in them as well. The resulting JavaScript will be (truncated):

var json = '...,\"TickSize\":\"[1, 'day']\"}';

Because of the now 4-count of single-quotes, day isn't actually part of the string and creates a syntax error.

But, you shouldn't even need to quote and parse the JSON since it's derived from JavaScript syntax:

var data = <%= Model.Json %>;

If you need the string representation, you can either stringify it in JavaScript:

var json = JSON.stringify(data):

Or escape single-quotes within the string server-side:

var json = '<%= Model.Json.Replace("'", "\\'") %>';

It is because you have surrounded the string with ' instead of ". This is causing the string to terminate with your first '.

Rewrite your first line as

var json = "<%=Model.Json %>";

Solution : replace single backslash '\' with double '\\' back slash.
For Newline character '\n' to '\\n'
Works with Tooltip messages

本文标签: javascriptParsing JSON with special charactersStack Overflow