在JavaScript中将JSON字符串转换为数组

sar*_*rdo 2 javascript arrays string json jqplot

我正在使用jqPlot创建图表.图表的数据点来自使用GSON构建的JSON对象.图表数据点以JavaScript数组格式构建,因此保存要发送到客户端的数据的Java对象存储数据,如下所示:

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]...]]";
Run Code Online (Sandbox Code Playgroud)

x点是日期.

是否可以直接从JSON对象传递此数据,就好像它是一个JavaScript数组?目前,MyJsonObject.chartDataPoints被视为String,因此jqPlot($ .jqplot('chart1',MyJsonObject.chartDataPoints)不会绘制任何内容.

Mit*_*ell 8

一种选择是使用eval:

var arr = eval('(' + json_text + ')');
Run Code Online (Sandbox Code Playgroud)

以上是最简单且最广泛支持的方法,但只有eval在信任源时才应该使用它,因为它将执行任何JavaScript代码.

某些浏览器具有本机JSON解析器,在这种情况下,您可以执行以下操作:

var arr = JSON.parse(json_text);
Run Code Online (Sandbox Code Playgroud)

jQuery等第三方库也可以提供处理JSON的功能.在jQuery中,您可以执行以下操作:

var arr = jQuery.parseJSON(json_text);
Run Code Online (Sandbox Code Playgroud)

最底层的两种方法(使用解析器)是首选方法,因为它们提供了一定程度的保护.