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);

問題は、2 次元のテーブル「タブ」を動的に宣言すると機能しないことです。

    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

The problem is that arrays and objects are not the same thing.

Your first code creates an array of objects.

Your second code creates an array of arrays, but then sets non-numeric properties on those arrays. JS arrays are a type of object so it is not an error to set non-numeric properties, but stringify() will only include the numeric properties. You need to do this:

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);

You could also do this:

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"};

(Also, why stringify and then immediately parse to get back the same object?)

于 2012-08-17T02:23:14.407 に答える