0

我需要将一个表解析为 JSON,我找到了这个解决方案并且它有效:

    var tab=[{"value":"1.0","label":"Alabama"},{"value":"2.0","label":"Alaska"},        {"value":"3.0","label":"American Samoa"}];
    var myJsonString = JSON.stringify(tab);  
    var jsonData = $.parseJSON(myJsonString);

问题是当我动态声明二维表“选项卡”时它不起作用:

    var tab_desc1= new Array(3);
    tab_desc1[0]=new Array(2);
    tab_desc1[0]["value"]="1.0";
    tab_desc1[0]["label"]="Alabama";
    tab_desc1[1]=new Array(2);
    tab_desc1[1]["value"]="2.0";
    tab_desc1[1]["label"]="Alaska";
    tab_desc1[2]=new Array(2);
    tab_desc1[2]["value"]="3.0";
    tab_desc1[2]["label"]="American Samoa";
    var myJsonString = JSON.stringify(tab_desc1);    
    var jsonData = $.parseJSON(myJsonString);

从逻辑上讲,我的声明包含错误,但我看不到它。任何帮助!谢谢。

4

2 回答 2

2
tab_desc1[0] = new Array(2);

应该

tab_desc1[0] = {};

和其他人一样。

但我不知道将变量字符串化为字符串然后将其解析回来的目的。

于 2012-08-17T02:20:49.220 回答
1

问题是数组和对象不是一回事。

您的第一个代码创建了一个对象数组。

您的第二个代码创建一个数组数组,然后在这些数组上设置非数字属性。JS 数组是一种对象,因此设置非数字属性不会出错,但stringify()只会包含数字属性。你需要这样做:

var tab_desc1 = []; // Note that [] is "nicer" than new Array(3)
tab_desc1[0] = {};  // NOTE the curly brackets to create an object not an array
tab_desc1[0]["value"] = "1.0";
tab_desc1[0]["label"] = "Alabama";
tab_desc1[1] = {};  // curly brackets
tab_desc1[1]["value"] = "2.0";
tab_desc1[1]["label"] = "Alaska";
tab_desc1[2] = {};  // curly brackets
tab_desc1[2]["value"] = "3.0";
tab_desc1[2]["label"] = "American Samoa";

var myJsonString = JSON.stringify(tab_desc1);    
var jsonData = $.parseJSON(myJsonString);

你也可以这样做:

var tab_desc1 = [];
tab_desc1[0] = {"value":"1.0","label":"Alabama"};
tab_desc1[1] = {"value":"2.0","label":"Alaska"};
tab_desc1[2] = {"value":"3.0","label":"American Samoa"};

(另外,为什么要字符串化然后立即解析以取回相同的对象?)

于 2012-08-17T02:23:14.407 回答