Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.stringify(array) surrounded with square brackets

I'm trying to get an array of data to insert into multiple columns in an sqlite database, I'v got it almost working with this:

function InsertData(dbData){
  var valueArray = [], dataArray = [];
  var values = Object.keys(dbData);
  for(var key in values){
    valueArray[valueArray.length] = values[key];
    dataArray[dataArray.length] = dbData[values[key]];
  }
  console.log("INSERT INTO "+dbData.table+" ("+valueArray+") VALUES ("+JSON.stringify(dataArray)+")");
  dbData.database.serialize(function(){
    dbData.database.run("INSERT INTO "+dbData.table+" ("+valueArray+") VALUES ("+JSON.stringify(dataArray)+")");
  });
}

My data is constructed as so:

//app.js
function EventData(title, value, other){
  this.title = title;
  this.value = value;
  this.other = other;
}
EventData.prototype = new dbtools.DBData(usuevents, 'event');
var thisEventData = new EventData('newData', 4, 2);

//dbtools.js
DBData = function(database, table){
  this.database = database;
  this.table = table;
};

the console.log outputs INSERT INTO event (title,value,other) VALUES (["newData",4,2]) I just need the [] square brackets removed on (["newData",4,2]). How would I do this? Also if there is a better way to insert data into sqlite im open to suggestions. Thanks

like image 362
Devcon Avatar asked Apr 19 '15 23:04

Devcon


2 Answers

JSON.stringify(dataArray) will always return square brackets because dataArray is of type array. Instead, you could stringify each element of your array, then join them separated by commas.

dataArray = dataArray.map(function(e){
  return JSON.stringify(e);
});

dataString = dataArray.join(",");

Then

["newData",4,2]

becomes

"newData",4,2

Addendum: Please don't try to replace() out the brackets manually because it could be that one day a bracket enters your array in a string. e.g. ["Please see ref[1]",4,2]

like image 125
Drakes Avatar answered Oct 05 '22 07:10

Drakes


Thanks Drakes and S McCrohan for your answers. I found that .replace(/]|[[]/g, '') appended to JSON.stringify(dataArray)

full line JSON.stringify(dataArray).replace(/]|[[]/g, '')

like image 44
Devcon Avatar answered Oct 05 '22 08:10

Devcon