2017-05-17 214 views
0

我正在處理將表數組轉換爲JSON的函數,這是我的代碼。我檢查過strJSON是我想要的JSON格式,但它是一個字符串而不是一個JSON對象。當我嘗試使用「eval」將其轉換爲JSON時,會出現一條錯誤消息,提示「Darren未定義」。我不知道發生了什麼事。將表數組轉換爲JSON對象

var myArray=[["Name","Age","Gender"],["Darren",31,"Male"],["Gakki",25,"Female"]]; 

//expected output 
var myJSON=[{"Name":"Darren","Age":31,"Gender":"Male"},{"Name":"Gakki","Age":25,"Gender":"Female"}]; 

function convertJSON(tableData){ 
    var objJSON=[]; 
    var strJSON=[]; 
    tableData.forEach(function(rowData,i){ 
     if (i==0){ 
      rowData.forEach(function(cellData){ 
       head.push(cellData); 
      }); 
     } 
     else{ 
      var objData=[]; 
      var objEntry=[]; 
      rowData.forEach(function(cellData,j){ 
       objData=head[j] + ":" + cellData; 
       objEntry.push(objData); 
      }); 
      strJSON.push("{" + objEntry + "}"); 
     } 
    }); 
    objJSON=eval("[" + strJSON + "]"); 
    return objJSON 
} 
+0

你沒有的東西轉換成JSON與EVAL,你可以使用'JSON.parse',你甚至都不需要做,在這一點,因爲strJSON將JSON如果已經你做得對。 –

回答

0

不要嘗試手動創建JSON字符串。把一個普通物體放在一起,並用JSON.stringify進行轉換。

var myArray=[["Name","Age","Gender"],["Darren",31,"Male"],["Gakki",25,"Female"]]; 
 

 
//expected output 
 
var myJSON=[{"Name":"Darren","Age":31,"Gender":"Male"},{"Name":"Gakki","Age":25,"Gender":"Female"}]; 
 

 
function convertJSON(tableData){ 
 
    var keys = tableData[0], 
 
     objects = []; 
 
     
 
    for(var i = 1; i < tableData.length; i++){ 
 
     var rowObject = {}; 
 
     tableData[i].forEach(function(item, index){ 
 
      rowObject[keys[index]] = item; 
 
     }); 
 
     objects.push(rowObject); 
 
    } 
 
    
 
    return JSON.stringify(objects); 
 
} 
 

 
document.write(convertJSON(myArray));

+0

myArray在shift()後被修改,如何保持它不變? – mogcai

+0

我編輯了代碼,因此它不需要調用'shift()',並保持原始數組完好無損。 – AndrewR

2
  1. 送一種元素和Array#shift
  2. 刪除原陣列然後使用Array#map建立自己的期望導致

var myArray=[["Name","Age","Gender"],["Darren",31,"Male"],["Gakki",25,"Female"]]; 
 

 
var properties = myArray.shift(); 
 

 
var result = myArray.map(a => { 
 
    var newObj = {}; 
 
    properties.forEach ((p, idx) => { 
 
    newObj[p] = a[idx]; 
 
    }); 
 
    return newObj; 
 
}) 
 

 
console.log(result);

0
function html2json() { 
    var json = '{'; 
    var otArr = []; 
    var tbl2 = $('#dest_table tr').each(function(i) {   
     x = $(this).children(); 
     var itArr = []; 
     x.each(function() { 
     itArr.push('"' + $(this).text() + '"'); 
     }); 
     otArr.push('"' + i + '": [' + itArr.join(',') + ']'); 
    }) 
    json += otArr.join(",") + '}' 

    return json; 
}