将JSON字符串解析为数组

时间:2012-07-12 21:42:33

标签: javascript json

我正在尝试从JSON解析字符串并将这些元素转换为Javascript中的数组。这是代码。

      var data = "{"fname":"Todd","lname":"James","cascade":"tjames","loc":"res","place":"home", "day0":"0,1,2,3,"}";
      var getDay = data.day0;
      var getDayArray = getDay.split(",");

基本上,我正在尝试获取day0,即0,1,2,3,并将其转换为结构为

的数组
[0] = 0
[1] = 1
[2] = 2
[3] = 3

这样做的最佳方式是什么?

3 个答案:

答案 0 :(得分:4)

像这样的东西。这个尾随逗号是故意的吗?

var getDayArray = JSON.parse(data).day0.split(",")

答案 1 :(得分:0)

这是内置于大多数现代浏览器JavaScript引擎中的。根据您定位的环境,您可以执行以下操作:

var data = JSON.parse(jsonString);
day0 = data.day0.split(",");

这很简单。如果您的目标是无法访问内置JSON对象的环境,则应尝试this JSON project

答案 2 :(得分:0)

大多数现代浏览器都支持JSON.parse()。你会这样使用它:

  var dataJSON = '{"fname":"Todd","lname":"James","cascade":"tjames","loc":"res","place":"home", "day0":"0,1,2,3"}'; // You need to remove the trailing comma
  var data = JSON.parse(dataJSON);
  var getDay = data.day0;
  var getDayArray = getDay.split(",");

但是,最好修改为dataJSON生成值的任何内容,以返回

  var dataJSON = '{"fname":"Todd","lname":"James","cascade":"tjames","loc":"res","place":"home", "day0":[0,1,2,3]}';