我有一个像字符串一样的JSON对象,它由函数tableToJson()返回。这就是它的样子。
{
{"Item Code":"sthing","Product Name":"sthing","Qantity":"1","Unit Price":"0","Item Total":"0"},
{"Item Code":"sthing","Product Name":"sthing","Qantity":"1","Unit Price":"0","Item Total":"0"},
{"Item Code":"sthing","Product Name":"sthing","Qantity":"1","Unit Price":"0","Item Total":"0"},
{"Item Code":"sthing","Product Name":"sthing","Qantity":"1","Unit Price":"0","Item Total":"0"}
}
如何在firebase数据库中保存它。 我已经在JS上面保存了一些数据,如下所示:
var databaseRef = firebase.database().ref('Bills');
function submitData(e){
e.preventDefault();
//variables for getting all values
var receiptDate = document.getElementById('date').innerHTML;
var receiptTime = document.getElementById('time').innerHTML;
var receiptBillNo = getInputValues('billNo');
var receiptCompName = getInputValues('companyName');
var receiptEmail = getInputValues('email');
var receiptPhone = getInputValues('phone');
var discount = getInputValues('Discount');
var total = getInputValues('sumTotal');
var newDataref = databaseRef.push();
var itemsJson = tableToJson();//THIS WILL RETURN THE ABOVE JSON STRING
//itemsJson = tableToJson();
//JSON.parse(itemsJson);
newDataref.set({
date: receiptDate,
time: receiptTime,
billNo: receiptBillNo,
company: receiptCompName,
email: receiptEmail,
phone: receiptPhone,
discount: discount,
total:total,
zitems: itemsJson
});
}
看看我的tableToJson()
function tableToJson(){
var tableId = document.getElementById('dataEntryTable');
var headName;
var headers = [];
var dataArray = [];
var rowCount = tableId.rows.length;
var colCount = tableId.rows[0].cells.length;
dataArray.push("[");
for(var i = 1; i < colCount; i++){
headName = tableId.rows[0].cells[i].innerHTML;
headers.push(headName);
}
console.log(headers);
for(var i = 1; i < rowCount; i++){
dataArray.push("\n{");
//FOR FIRST APPROACH:dataArray.push("\n/"" + i + "/" :{");
for(var j = 1; j < colCount; j++){
var currValue = tableId.rows[i].cells[j].childNodes[0].value;
dataArray.push("\"" + headers[j-1] + "\":" + "\"" + currValue +
"\"");
if(j < (colCount - 1)){
dataArray.push(",");
}
}
if( i < (rowCount - 1)){
dataArray.push("},");
}
else{
dataArray.push("}/n");
}
}
dataArray.push("]");
return dataArray.join("");
}
此代码有问题。 即使我将其解析为JSON,它也会以字符串形式发送。
答案 0 :(得分:1)
可以将JSON字符串转换回js对象:
newDataref.set({
date: receiptDate,
/*...*/
zitems: JSON.parse(itemsJson)
});
但完全没有字符串化它会更好。