Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
86
rated 0 times [  90] [ 4]  / answers: 1 / hits: 16480  / 12 Years ago, mon, november 5, 2012, 12:00:00

I'm using jqPlot to create a chart. The data points for the chart come from a JSON object which is built using GSON. The chart data points are built in a JavaScript array format, so the Java object that holds the data to send to the client stores the data as follows:



String chartDataPoints = [[1352128861000, 0.0], [1352128801000, 0.0], [1352128741000,   0.0], [1352128681000, 0.0], [1352128621000, 0.0],...More chart points in this format ,[[x0,y0], [x1,y2]...]];


The x points are dates.



Is it possible to pass this data straight from the JSON object as though it is a JavaScript array? Currently MyJsonObject.chartDataPoints is treated as a String, and so jqPlot ($.jqplot ('chart1', MyJsonObject.chartDataPoints) doesn't plot anything.


More From » arrays

 Answers
39

One option is to use eval:



var arr = eval('(' + json_text + ')');


The above is easiest and most widely supported way of doing this, but you should only use eval if you trust the source as it will execute any JavaScript code.



Some browsers have a native JSON parser in which case you can do the following:



var arr = JSON.parse(json_text);


Third-party libraries such as jQuery can also provide functions for dealing with JSON. In jQuery, you can do the following:



var arr = jQuery.parseJSON(json_text);


The bottom two methods (which use a parser) are preferred as they provide a level of protection.


[#82180] Sunday, November 4, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
danar

Total Points: 271
Total Questions: 94
Total Answers: 93

Location: Ecuador
Member since Thu, Jun 4, 2020
4 Years ago
;