Updating data in json file - json

I want to update values in my Data.json file.
{
"A0_Water":"-306.3",
"A1_Water":"0.0",
"A2_Water":"0.0",
"A3_Water":"0.0",
"Barometer":"100.8",
"Bar_Offset":"0",
"Temp":"29.95",
"ip":"192.168.2.47",
"serial":"02:42:52:bf:82:27",
"A0_Sensor":"PS30A",
"A1_Sensor":"None",
"A2_Sensor":"None",
"A3_Sensor":"None",
"A0_Offset":"0",
"A1_Offset":"0",
"A2_Offset":"0",
"A3_Offset":"0"
}
The code that I have working:
I am currently not using var data object to update the Data.json file
var data = {
'A0_Water': c_inh2o_A0,
'A1_Water': c_inh2o_A1,
'A2_Water': c_inh2o_A2,
'A3_Water': c_inh2o_A3,
'Barometer': b_mbar_corrected,
'Temp': b_temp
};
var fileName = '/home/admin/reactwatertracker/src/var/Data.json';
var file4 = require(fileName);
var file5 = file4;
var file6 = file4;
var file7 = file4;
var file8 = file4;
var file9 = file4;
file4['A0_Water'] = c_inh2o_A0;
file5['A1_Water'] = c_inh2o_A1;
file6['A2_Water'] = c_inh2o_A2;
file7['A3_Water'] = c_inh2o_A3;
file8['Temp'] = b_temp;
file9['Barometer'] = b_mbar_corrected;
console.log('Writing to' + fileName);
fs.writeFile(fileName, JSON.stringify(file4,file5,file6,file7,file8,file9, null, 2), function (err) {
if (err) return console.log(err);
console.log (JSON.stringify(file4));
});

Related

find all label and product in json python

I'm trying to find all label and product in text/javascript, but I don't have any idea to how do it. I'm trying to parse label, id and products.
var spConfigDisabledProducts = [-1
, '290058', '290060', '290061', '290062', '290063', '290065', '290071', '290073', '290075', '290076', '290077', '290078' ];
var spConfig = new Product.Config({"attributes":{"959":{"id":"959","code":"aw_taglia","label":"Taglia","options":[{"id":"730","label":"36 ½","price":"0","oldPrice":"0","products":["290058"]},{"id":"731","label":"37 ½","price":"0","oldPrice":"0","products":["290060"]},{"id":"732","label":"38","price":"0","oldPrice":"0","products":["290061"]},{"id":"733","label":"38 ½","price":"0","oldPrice":"0","products":["290062"]},{"id":"734","label":"39","price":"0","oldPrice":"0","products":["290063"]},{"id":"735","label":"40","price":"0","oldPrice":"0","products":["290064"]},{"id":"736","label":"40 ½","price":"0","oldPrice":"0","products":["290065"]},{"id":"737","label":"41","price":"0","oldPrice":"0","products":["290066"]},{"id":"738","label":"42","price":"0","oldPrice":"0","products":["290067"]},{"id":"739","label":"42 ½","price":"0","oldPrice":"0","products":["290068"]},{"id":"740","label":"43","price":"0","oldPrice":"0","products":["290069"]},{"id":"741","label":"44","price":"0","oldPrice":"0","products":["290070"]},{"id":"742","label":"44 ½","price":"0","oldPrice":"0","products":["290071"]},{"id":"743","label":"45","price":"0","oldPrice":"0","products":["290072"]},{"id":"744","label":"45 ½","price":"0","oldPrice":"0","products":["290073"]},{"id":"745","label":"46","price":"0","oldPrice":"0","products":["290074"]},{"id":"746","label":"47","price":"0","oldPrice":"0","products":["290075"]},{"id":"747","label":"47 ½","price":"0","oldPrice":"0","products":["290076"]},{"id":"748","label":"13.5","price":"0","oldPrice":"0","products":["290077"]},{"id":"749","label":"48 ½","price":"0","oldPrice":"0","products":["290078"]}]}},"template":"#{price}\u00a0\u20ac","basePrice":"130","oldPrice":"130","productId":"290059","chooseText":"Seleziona","taxConfig":{"includeTax":true,"showIncludeTax":true,"showBothPrices":false,"defaultTax":0,"currentTax":0,"inclTaxTitle":"Incl. Tasse"}});
jQuery("#attribute959 option").each(function () {
var option = jQuery(this);
var id = option.attr('value');
jQuery.each(spConfig.config.attributes, function () {
jQuery.each(this.options, function () {
if (this.id == id) {
if (spConfigDisabledProducts.indexOf(this.products[0]) >= 0) {
option.data('disabled', true);
}
}
});
});
});
It's possible to do that less elegantly but without regex - just a series of splits and clean ups:
import json
code = [your script above]
code2 = html.replace('½','').split('":"Taglia","options":[{')[1].split('}]}},"template"')[0].split('},{')
for i in range(len(code2)):
data = json.loads('{'+code2[i]+'}')
print(data['id'],data['label'])
Output:
730 36
731 37
732 38
733 38
etc.
You can regex out javascript object and pass to json then parse out info
import re
import json
#html = response.content from requests
html = '''
var spConfigDisabledProducts = [-1
, '290058', '290060', '290061', '290062', '290063', '290065', '290071', '290073', '290075', '290076', '290077', '290078' ];
var spConfig = new Product.Config({"attributes":{"959":{"id":"959","code":"aw_taglia","label":"Taglia","options":[{"id":"730","label":"36 ½","price":"0","oldPrice":"0","products":["290058"]},{"id":"731","label":"37 ½","price":"0","oldPrice":"0","products":["290060"]},{"id":"732","label":"38","price":"0","oldPrice":"0","products":["290061"]},{"id":"733","label":"38 ½","price":"0","oldPrice":"0","products":["290062"]},{"id":"734","label":"39","price":"0","oldPrice":"0","products":["290063"]},{"id":"735","label":"40","price":"0","oldPrice":"0","products":["290064"]},{"id":"736","label":"40 ½","price":"0","oldPrice":"0","products":["290065"]},{"id":"737","label":"41","price":"0","oldPrice":"0","products":["290066"]},{"id":"738","label":"42","price":"0","oldPrice":"0","products":["290067"]},{"id":"739","label":"42 ½","price":"0","oldPrice":"0","products":["290068"]},{"id":"740","label":"43","price":"0","oldPrice":"0","products":["290069"]},{"id":"741","label":"44","price":"0","oldPrice":"0","products":["290070"]},{"id":"742","label":"44 ½","price":"0","oldPrice":"0","products":["290071"]},{"id":"743","label":"45","price":"0","oldPrice":"0","products":["290072"]},{"id":"744","label":"45 ½","price":"0","oldPrice":"0","products":["290073"]},{"id":"745","label":"46","price":"0","oldPrice":"0","products":["290074"]},{"id":"746","label":"47","price":"0","oldPrice":"0","products":["290075"]},{"id":"747","label":"47 ½","price":"0","oldPrice":"0","products":["290076"]},{"id":"748","label":"13.5","price":"0","oldPrice":"0","products":["290077"]},{"id":"749","label":"48 ½","price":"0","oldPrice":"0","products":["290078"]}]}},"template":"#{price}\u00a0\u20ac","basePrice":"130","oldPrice":"130","productId":"290059","chooseText":"Seleziona","taxConfig":{"includeTax":true,"showIncludeTax":true,"showBothPrices":false,"defaultTax":0,"currentTax":0,"inclTaxTitle":"Incl. Tasse"}});
jQuery("#attribute959 option").each(function () {
var option = jQuery(this);
var id = option.attr('value');
jQuery.each(spConfig.config.attributes, function () {
jQuery.each(this.options, function () {
if (this.id == id) {
if (spConfigDisabledProducts.indexOf(this.products[0]) >= 0) {
option.data('disabled', true);
}
}
});
});
});'''
p = re.compile(r'Product\.Config\((.*?)\)', re.DOTALL)
data = json.loads(p.findall(html)[0])
for attribute in data['attributes']:
print('-----------------attribute--------------')
print('label = ' + data['attributes'][attribute]['label'], 'id = ' + data['attributes'][attribute]['id'])
print('-----------------options----------------')
for product in data['attributes'][attribute]['options']:
print('label = ' + product['label'], 'id = ' + product['id'], 'product = ' + product['products'][0])

asp.net razor core insert multiple records on post

I trying to create an email log when an email is sent.
I have created a foreach loop to add the records to the database.
However, I can only get it to add one record when the await _context.SaveChangesAsync(); is outside the loop.
If I put await _context.SaveChangesAsync(); inside I get the following error.
SqlException: Cannot insert explicit value for identity column in table 'EmailLog' when IDENTITY_INSERT is set to OFF
Code:
public async Task<IActionResult> OnPostAsync(IEnumerable<int> emailuser)
{
//get login user
var claimsIdentity = (ClaimsIdentity)this.User.Identity;
var claim = claimsIdentity.FindFirst(ClaimTypes.Name);
var TestAimItem = _context.AimItem.Where(x => emailuser.Contains(x.Id)).ToList();
foreach (var item in TestAimItem.GroupBy(item => item.Email))
{
EmailMessage = await _context.EmailMessage.SingleOrDefaultAsync(m => m.Id == 2);
string EmailAddress = (item.Key);
var emailMessage1 = EmailMessage.MessageBody.Replace(Environment.NewLine, "<br/>");
var linkHtml = "here";
var emailMessage2 = emailMessage1.Replace("HPWDLINK", "click " + linkHtml);
var emailMessage3 = emailMessage2.Replace("HPWDUSEREMAIL", EmailAddress);
var emailMessage4 = HttpUtility.HtmlDecode(emailMessage3);
await _emailSender.SendEmailAsync(To, EmailMessage.MessageSubject, emailMessage4);
}
foreach (var item1 in TestAimItem)
{
EmailLog.EmailDate = DateTime.Now;
EmailLog.MessageId = 2;
EmailLog.SentTo = item1.Email;
EmailLog.SentBy = claim.Value;
//submit record
_context.EmailLog.Add(EmailLog);
//await _context.SaveChangesAsync();
}
await _context.SaveChangesAsync();
return RedirectToPage("/UserReporting/EmailUsersAnnualReport");
}

Node.js pushing data into Excel is not working

Hi I am trying to push data from my array of queries into excel but only the header seems to be displayed but the results are being pushed. When I did a console.log to see whether they would be pushed it says undefined. Any ideas as to why?
Example code:
var excel_data=[];
excel_data.push=(['Source', 'Count of thing 1', 'Count of thing 2', 'Count of thing 3']);
var database = new database(config);
var query_array = ['select count(*) as count_of_thing1 from table1', 'select count(*) as count_of_thing2 from table2', 'select count(*) as count_of_thing3 from table3'];
query_array.forEach(q => {
database.query(q)
.then(rows => {
_.each(rows, function(row){
excel_data.push([row.count_of_thing1, row.count_of_thing2, row.count_of_thing3]);
});
})
var wb = XLSX.utils.book_new();
var ws_name = "Query_Results";
var wscols = [ {width: 15} ];
var wsrows = [];
var ws = XLSX.utils.aoa_to_sheet(excel_data, {cellDates:true});
ws['!cols'] = wscols;
ws['!rows'] = wsrows;
XLSX.utils.book_append_sheet(wb, ws, ws_name);
var filenames = [
['mysql.xlsx', {bookSST:true}],
['mysql.csv', {bookSST:true}],
];
filenames.forEach(function(r) {
XLSX.writeFile(wb, r[0], r[1]);
XLSX.readFile(r[0]);
});
});

Upload Excel using nodejs

I am uploading an Excel file and inserting into a mysql table. My code is working with Linux. But I want it should run with other also so I am predicting that Xls is not working.
How to change into CSV or any other way so we can upload the Excel or csv which support any version?
function getfileDetails(req, res) {
var sampleFile, fileInfo = {};
var date1=new Date();
var currdatetime = date1.getFullYear()+"-"+(date1.getMonth()+1)+"-"+date1.getDate()+" "+date1.getHours()+":"+date1.getMinutes()+":"+date1.getSeconds();
console.log(currdatetime);
var MyData = [];
if (!req.files) {
res.send('No files were uploaded.');
return;
}
sampleFile = req.files.fileInputXLSX1;
var datetimestamp = Date.now();
console.log("Uploaded -- ",sampleFile);
var fileExtn = sampleFile.name.split(".").pop();
var extractedFilename = sampleFile.name.slice(0, sampleFile.name.lastIndexOf('.'));
var userid=req.headers['userid'];
var uploadFileName = extractedFilename+'_'+userid+'_'+datetimestamp+'.'+fileExtn;
console.log("uploadFileName -- ",uploadFileName);
fileInfo = {
"name": uploadFileName,
"mimetype": sampleFile.mimetype
}
// Use the mv() method to place the file somewhere on your server
sampleFile.mv(__dirname+'/Details/'+uploadFileName, function(err) {
if (err) {
res.status(500).send(err);
}
var parseXlsx = require('excel');
parseXlsx(__dirname+'/Details/'+uploadFileName, function(err, data) {
if(err) throw err;
// data is an array of arrays
else{
if(data!=null)
{
var queryString= "Truncate table `details`;"
connection.query(queryString, function(err,result){
if(err) {
res.write(JSON.stringify(err));
res.end();
} else {
res.send('File uploaded!');
}
});
}
for (var index = 1; index < data.length; index++)
{
MyData.push(data[index][0],data[index][1],data[index][2],data[index][3], data[index][4], data[index][5],data[index][6],data[index][7],data[index][8],data[index][9]);
var queryString="INSERT INTO `details`(name,tname,fname,timestamp) VALUES ('"+data[index][0]+"','"+data[index][1]+"','"+data[index][2]+"','"+currdatetime+"')";
connection.query(queryString, function(err,result){
if(err) {
res.write(JSON.stringify(err));
res.end();
} else {
res.send('File uploaded!');
}
});
}
}
});
if(err) {
res.status(500);
res.send(err);
}
});
}
Please help ,I am New in Node.
hey can you try json2csv npm module. this will solve you problem #TB.M
This code is working fine, try this..
var xlsx = require('node-xlsx');
var fs = require('fs');
var obj = xlsx.parse(__dirname + '/new.xls'); // parses a file
var rows = [];
var writeStr = "";
//looping through all datarow
for(var i = 0; i < obj.length; i++)
{
var dataRow = obj[i];
//loop through all rows in the sheet
for(var j = 0; j < dataRow['data'].length; j++)
{
//add the row to the rows array
rows.push(dataRow['data'][j]);
}
}
//creates the csv string to write it to a file
for(var i = 0; i < rows.length; i++)
{
writeStr = writeStr + rows[i].join(",") + "\n";
}
//writes to a file, but you will presumably send the csv as a
//response instead
fs.writeFile(__dirname + "/data.csv", writeStr, function(err) {
if(err) {
return console.log(err);
}
console.log("data.csv was saved in the current directory!");
});

how to convert into a json object

i have a file named 'funcJson.json'
whose content are as follows:
{
"fid":{
"processDate":function ()
{
data=MainMasterarr;
for(var i=0;i<data.length;i++)
{
data[i]['_id'] =data[i]['_id'].substring(0,8);
var mongoId = data[i]["_id"];
var dateObject = new Date( mongoId );
dateObject = new Date( parseInt( mongoId, 16 ) * 1000 );
var date = dateObject.getDate();
var month = dateObject.getMonth()+1;
var year = dateObject.getFullYear().toString();
var yearSub = year.substring(2,4);
if(month<10)
month='0'+ month;
if (date<10)
date='0'+ date;
var dateString = month+'/'+date+'/'+yearSub;
data[i]['fid'] = dateString;
}
} ,
"consoleDate":function ()
{
data=MainMasterarr;
console.log(data[0]['fid']);
}
}
}
now i trying to read this file and convert the file content to json object.
when i equate the above json to a variable.it works like json object but now when i m trying to read it from a file it throws error.
my client side code is below:
function fetchFileData(fn,callback)
{
var fileName='funcJson.json';
var request = new goog.net.XhrIo();
var data = goog.Uri.QueryData.createFromMap(new goog.structs.Map({
"fileN":fileName,
}));
goog.events.listen(request, "complete", function()
{
if (request.isSuccess())
{
if(request.getResponseText() == 'fails')
{
callback("error");
return;
} //if response fails
else
{
var response = request.getResponseJson();
fileData=response;
console.log(fileData);
callback(response);
}//else
} //if request is success
});//listen event
request.send(fetchFileUrl, "POST", data);
//return fileData;
};
and server side code is as follows
function fetchFile(req,res,params)
{
var fs = require('fs');
//var configJson = {};
var fileName=params.fileN;
fs.readFile(fileName, 'utf8', function (err, data) {
if (err)console.log(err);
//console.log(data);
//configJson = JSON.parse(data);
res.writeHead(200, {
"Content-Type": "text/plain"
});//res.writeHead
res.write(data);
res.end();
});
}
If i take a normal json with functions in it give me result as object which i can instantiate to variable and use that variable as json object.but as i give function declaration in json file.it throws error.
plz guide
changed the json format and it worked
format is as follows:
{
"fid":{
"processDate":"function (){data=MainMasterarr;for(var i=0;i<data.length;i++){data[i]['_id'] =data[i]['_id'].substring(0,8);var mongoId = data[i]['_id'];var dateObject = new Date( mongoId );dateObject = new Date( parseInt( mongoId, 16 ) * 1000 );var date = dateObject.getDate();var month = dateObject.getMonth()+1;var year = dateObject.getFullYear().toString();var yearSub = year.substring(2,4);if(month<10)month='0'+ month;if (date<10)date='0'+ date;var dateString = month+'/'+date+'/'+yearSub;data[i]['fid'] = dateString;}}",
"consoleDate":"function (){data=MainMasterarr;console.log(data[0]['fid']);}"
},
"nloc":{
"processDate":"function (){data=MainMasterarr;for(var i=0;i<data.length;i++){data[i]['_id'] =data[i]['_id'].substring(0,8);var mongoId = data[i]['_id'];var dateObject = new Date( mongoId );dateObject = new Date( parseInt( mongoId, 16 ) * 1000 );var date = dateObject.getDate();var month = dateObject.getMonth()+1;var year = dateObject.getFullYear().toString();var yearSub = year.substring(2,4);if(month<10)month='0'+ month;if (date<10)date='0'+ date;var dateString = month+'/'+date+'/'+yearSub;data[i]['fid'] = dateString;}}",
"consoleDate":"function (){data=MainMasterarr;console.log(data[0]['fid']);}"
}
}