Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
530 views
in Technique[技术] by (71.8m points)

javascript - Parsing JSON with special characters

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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("'", "\'") %>';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...