0

I am working on a function for converting a table array to JSON and this is my code. I have checked strJSON is the JSON format I want, but it is a string instead of an JSON object. An error message prompts out saying that "Darren is not defined" when I try to convert it into JSON with "eval". I dont know what is happening.

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
}
1
  • You don't convert things into JSON with eval, you use JSON.parse and you don't even need to do that at this point since strJSON would be JSON already if you did it right. Commented May 17, 2017 at 6:13

3 Answers 3

3
  1. Get 1 element and remove it in original array by Array#shift
  2. Then use Array#map to build your expect result

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

Sign up to request clarification or add additional context in comments.

Comments

0

Don't try to create a JSON string manually. Put together a normal object and use JSON.stringify to convert.

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

2 Comments

myArray is being modified after shift();, How to keep it unchange?
I edited the code so it doesn't need to call shift(), and leaves your original array intact.
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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.