Vue Export JSON to csv file - json

I am trying to export JSON to a CSV file.
Previously I'm using this code below to export:
convertToCSV(objArray: any) {
var array = typeof objArray != "object" ? JSON.parse(objArray) : objArray;
var str = "";
for (var i = 0; i < array.length; i++) {
var line = "";
for (var index in array[i]) {
if (line != "") line += ",";
line += array[i][index];
}
str += line + "\r\n";
}
return str;
}
exportCSVFile(headers: any, items: any[], fileTitle: string) {
if (headers) {
items.unshift(headers);
}
// Convert Object to JSON
var jsonObject = JSON.stringify(items);
var csv = this.convertToCSV(jsonObject);
var exportedFilenmae = fileTitle + ".csv" || "export.csv";
var blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
if (navigator.msSaveBlob) {
// IE 10+
navigator.msSaveBlob(blob, exportedFilenmae);
} else {
var link = document.createElement("a");
if (link.download !== undefined) {
// feature detection
// Browsers that support HTML5 download attribute
var url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", exportedFilenmae);
link.style.visibility = "hidden";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
}
exportcsv() {
this.data.forEach((item) => {
this.itemsFormatted.push({
meteringpoint: item.meteringpoint.replace(/,/g, ""), // remove commas to avoid errors,
group: item.group,
instdevice: item.instdevice,
floor: item.floor,
room: item.room,
section: item.section,
});
});
var fileTitle = "Metering Point View"; // or 'my-unique-title'
this.exportCSVFile(this.headerCSV, this.itemsFormatted, fileTitle);
}
}
But there's an error with Property 'msSaveBlob' does not exist on type 'Navigator'
Here is what I found on the internet regarding the error
So I want to ask if there is any library for exporting that has a typescript definition or is there any workaround for the problem on the code above.
Most of the libraries i found will have this problem whereby Could not find a declaration file for module 'vue-json-to-csv'. 'd:/Project/Ivory-Leaf/OAMR/VueFrontEndUi/vuefrontendui/node_modules/vue-json-to-csv/dist/vue-json-to-csv.js' implicitly has an 'any' type. Try `npm i --save-dev #types/vue-json-to-csv` if it exists or add a new declaration (.d.ts) file containing `declare module 'vue-json-to-csv';

Related

How remove invalid or specific files from fileupload in prime ng p-fileUpload?

I have used file upload for uploading files and I want to validate the files when I select one of them and remove it if that is not a valid file.
.html
<p-fileUpload #fileUpload name="datafiles"
[accept]=FileExtentionValue
[url]="FileUploadUrl"
[showUploadButton]="isUploadEnable"
[disabled]="diableFileupload"
(onUpload)="onUpload($event)"
(onSelect)="validateFile($event)"
multiple="multiple">
</p-fileUpload>
.ts
onUpload(event) {
for (let file of event.files) {
this.uploadedFiles.push(file);
}
this.messageService.add({ severity: 'info', summary: 'File Uploaded', detail: '' });
}
validate filles name
validateFile(event) {
let tempFiles: any = [];
var FileNmaeMust: any;
for (let file of event.files) {
tempFiles.push(file.name);
}
for (let i = 0; i < tempFiles.length; i++) {
let count = 1;
for (let j = 0; j < this.ClientDataFileTypeValue.length; j++) {
FileNmaeMust = "";
if (this.ClientDataFileTypeValue[j] == "Order") {
FileNmaeMust = this.MPID + "_ORDER_";
}
/*** Validate File */
var templen = FileNmaeMust + "YYYYMMDD.psv";
if (tempFiles[i].includes((FileNmaeMust).toLocaleUpperCase()) && tempFiles[i].length == templen.length) {
this.isUploadEnable = true;
break;
}
if (count == this.ClientDataFileTypeValue.length) {
this.isUploadEnable = false;
this.messageService.add({ severity: 'error', summary: 'Files', detail: 'Please select correct file ' + tempFiles[i] });
}
count++;
}
}
}
I haved soved it using id .I have defined #fileUpload and pass it to (onSelect)="validateFile($event,fileUpload)" function to validate and remove this file from array.
<p-fileUpload #fileUpload name="datafiles"
[accept]=FileExtentionValu
[url]="FileUploadUrl"
[disabled]="isDiableFileupload"
[showUploadButton]="isUploadEnable"
(onSelect)="validateFile($event,fileUpload)" (onBeforeUpload)="onBeforeSend($event)"
(onUpload)="onUpload($event)"
multiple="multiple">
</p-fileUpload>
.ts
import {FileUpload } from 'primeng/primeng';
validateFile(event, uploader: FileUpload) {
let tempFiles: any = [];
var FileNmaeMust: any;
for (let file of event.files) {
tempFiles.push(file.name);
}
for (let i = 0; i < tempFiles.length; i++) {
let count = 1;
for (let j = 0; j < this.ClientDataFileTypeValue.length; j++) {
FileNmaeMust = "";
if (this.ClientDataFileTypeValue[j] == "Order") {
FileNmaeMust = this.MPID + "_ORDER_";
}
/*** Validate File */
var templen = FileNmaeMust + "YYYYMMDD.psv";
if (tempFiles[i].includes((FileNmaeMust).toLocaleUpperCase()) && tempFiles[i].length == templen.length) {
this.isUploadEnable = true;
break;
}
if (count == this.ClientDataFileTypeValue.length) {
this.isUploadEnable = false;
uploader.remove(event, i);
this.isUploadEnable = true;
this.messageService.add({ severity: 'error', summary: 'Files', detail: 'Please select correct file ' + tempFiles[i] });
}
count++;
}
}
}
onSelect Event - Callback to invoke when files are selected.
Official Documentation
Example:
<p-fileUpload #fileUpload name="datafiles"
[accept]=FileExtentionValue
[url]="FileUploadUrl"
[showUploadButton]="isUploadEnable"
(onUpload)="onUpload($event)" multiple="multiple"
(onSelect)="onSelect($event)">
</p-fileUpload>
onUpload(event) {
for (let file of event.files) {
this.uploadedFiles.push(file);
}
this.messageService.add({ severity: 'info', summary: 'File Uploaded', detail: '' });
}
onSelect(event) {
// event.originalEvent: Original browser event.
// event.files: List of selected files.
// Your validation code against list of selected files / selected file.
}
Hope this helps.,

Any tool to check circular dependency in a JSON schema

I am using JSON file and validated it on Swagger 2.0 Parser and validator
it validates it but give error of circular reference, is there any free tool or website to detect the position of circular reference in a file.
I think what you are looking for is already answered here.
Simply open your browser console and type this javascript :
function isCyclic(obj) {
var keys = [];
var stack = [];
var stackSet = new Set();
var detected = false;
function detect(obj, key) {
if (typeof obj != 'object') { return; }
if (stackSet.has(obj)) { // it's cyclic! Print the object and its locations.
var oldindex = stack.indexOf(obj);
var l1 = keys.join('.') + '.' + key;
var l2 = keys.slice(0, oldindex + 1).join('.');
console.log('CIRCULAR: ' + l1 + ' = ' + l2 + ' = ' + obj);
console.log(obj);
detected = true;
return;
}
keys.push(key);
stack.push(obj);
stackSet.add(obj);
for (var k in obj) { //dive on the object's children
if (obj.hasOwnProperty(k)) { detect(obj[k], k); }
}
keys.pop();
stack.pop();
stackSet.delete(obj);
return;
}
detect(obj, 'obj');
return detected;
}
Then you call IsCyclic(/*Json String*/), the result will show where the circular reference is.

String.fromCharCode and String.fromCodePoint are not working in react native app's apk

String.fromCharCode and String.fromCodePoint both are working fine in chrome developer tools and in the emulator but when i am generating the apk and running it on the actual android device, its not working.
According to MDN's String.fromCodePoint doc:
The String.fromCodePoint method has been added to ECMAScript 2015 and may not be supported in all web browsers or environments yet. Use the code below for a polyfill:
*! http://mths.be/fromcodepoint v0.1.0 by #mathias */
if (!String.fromCodePoint) {
(function() {
var defineProperty = (function() {
// IE 8 only supports `Object.defineProperty` on DOM elements
try {
var object = {};
var $defineProperty = Object.defineProperty;
var result = $defineProperty(object, object, object) && $defineProperty;
} catch(error) {}
return result;
}());
var stringFromCharCode = String.fromCharCode;
var floor = Math.floor;
var fromCodePoint = function() {
var MAX_SIZE = 0x4000;
var codeUnits = [];
var highSurrogate;
var lowSurrogate;
var index = -1;
var length = arguments.length;
if (!length) {
return '';
}
var result = '';
while (++index < length) {
var codePoint = Number(arguments[index]);
if (
!isFinite(codePoint) || // `NaN`, `+Infinity`, or `-Infinity`
codePoint < 0 || // not a valid Unicode code point
codePoint > 0x10FFFF || // not a valid Unicode code point
floor(codePoint) != codePoint // not an integer
) {
throw RangeError('Invalid code point: ' + codePoint);
}
if (codePoint <= 0xFFFF) { // BMP code point
codeUnits.push(codePoint);
} else { // Astral code point; split in surrogate halves
// http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
codePoint -= 0x10000;
highSurrogate = (codePoint >> 10) + 0xD800;
lowSurrogate = (codePoint % 0x400) + 0xDC00;
codeUnits.push(highSurrogate, lowSurrogate);
}
if (index + 1 == length || codeUnits.length > MAX_SIZE) {
result += stringFromCharCode.apply(null, codeUnits);
codeUnits.length = 0;
}
}
return result;
};
if (defineProperty) {
defineProperty(String, 'fromCodePoint', {
'value': fromCodePoint,
'configurable': true,
'writable': true
});
} else {
String.fromCodePoint = fromCodePoint;
}
}());
}
so you can try to polyfill String.fromCodePoint in your file

While exporting as csv file, file is getting downloaded but with name download and with no extension

While exporting as csv file, file is getting downloaded but with name as download and with no extension,
I tried searching solution but didn't got any.
below is the code. If I rename the file and save as csv it shows the correct data
_addPrintButton: function() {
var me = this;
this.down('#print_button_box').add( {
xtype: 'rallybutton',
itemId: 'print_button',
text: 'Export to Excel',
disabled: false,
margin: '20 10 10 0',
region: "right",
handler: function() {
me._onClickExport();
}
});
},
_onClickExport: function(){
var grid = this.down('#grid_box');
var data = this._getCSV(grid.items.items[0]);
window.location = 'data:text/csv;charset=utf8,' + encodeURIComponent(data);
//Ext.getBody().unmask();
},
_getCSV: function (grid) {
var cols = grid.columns;
var store = grid.store;
var data = '';
var that = this;
_.each(cols, function(col, index) {
data += that._getFieldTextAndEscape(col.text) + ',';
});
data += "\r\n";
_.each(that.records, function(record) {
_.each(cols, function(col, index) {
var text = '';
var fieldName = col.dataIndex;
text = record[fieldName];
if (text || text == 0) {
//text = record[fieldName];
data += that._getFieldTextAndEscape(text) + ',';
}
/*else if (fieldName === "Project" ) {
text = record[fieldName];
}
else if (fieldName === "Case") {
var size = _.size(record[fieldName]);
for (var i = 0; i < size; i++){
text = record[fieldName][i]
}
}*/
});
data += "\r\n";
});
return data;
},
_getFieldTextAndEscape: function(fieldData) {
var string = this._getFieldText(fieldData);
return this._escapeForCSV(string);
},
_getFieldText: function(fieldData) {
var text;
if (fieldData === null || fieldData === undefined) {
text = '';
} else if (fieldData._refObjectName) {
text = fieldData._refObjectName;
}else {
text = fieldData;
}
return text.toString();
},
_escapeForCSV: function(string) {
if (string.match(/,/)) {
if (!string.match(/"/)) {
string = '"' + string + '"';
} else {
string = string.replace(/,/g, '');
}
}
return string;
},
You're searching at the wrong place.
The web server has to add HTTP header Content-Disposition to indicate the recommended file name, e.g.
Content-Disposition: attachment; filename="correct_data.csv"

How convert tsv to Json

I want to make a dynamic graph based on a json file. I have seen many examples with tsv but I donot how to convert it to json.
That is the part that I want to change from tsv to json but I donot know how!
d3.tsv("data/data.tsv", function(error, data) {
data.forEach(function(d) {
d.date = parseDate(d.date);
d.close = +d.close;
});
when I use
d3.json("data/data.json", function(data) {
data.forEach(function d) {
d.date = parseDate(d.date);
d.close = +d.close;
}
});
it gives this error: Uncaught type error: cannot call method 'forEach' of undefined!
Thanks for your suggestions :)
try to do something like this
d3.json("data/data.json", function(data) {
data.forEach(function d) {
d.date = parseDate(d.date);
d.close = +d.close;
}
});
d3.js have support for json, https://github.com/mbostock/d3/wiki/Requests
The syntax around your forEach is a little off; try this instead:
d3.json("data/data.json", function(data) {
data.forEach(function(d) {
d.date = parseDate(d.date);
d.close = +d.close;
});
});
(As Felix points out, this will only work if your JSON object is defined and is an array)
Here a small code where you'll be able to convert tsv to json. It could help you...
ps : here is typescript, but you can easily convert it to vanilla javascript ;)
// Set bunch of datas into format object
tsvToJson(datas: string): Array<Object>{
// Separate each lines
let array_datas = datas.split(/\r\n|\r|\n/g);
// Separate each values into each lines
var detailed_datas = [];
for(var i = 0; i < array_datas.length; i++){
detailed_datas.push(array_datas[i].split("\t"));
}
// Create index
var index = [];
var last_index = ""; // If the index we're reading is equal to "", it mean it might be an array so we take the last index
for(var i = 0; i < detailed_datas[0].length; i++){
if(detailed_datas[0][i] == "") index.push(last_index);
else {
index.push(detailed_datas[0][i]);
last_index = detailed_datas[0][i];
}
}
// Separate data from index
detailed_datas.splice(0, 1);
// Format data
var formated_datas = [];
for(var i = 0; i < detailed_datas.length; i++){
var row = {};
for(var j = 0; j < detailed_datas[i].length; j++){
// Check if value is empty
if(detailed_datas[i][j] != ""){
if(typeof row[index[j]] == "object"){
// it's already set as an array
row[index[j]].push(detailed_datas[i][j]);
} else if(row[index[j]] != undefined){
// Already have a value, so it might be an array
row[index[j]] = [row[index[j]], detailed_datas[i][j]];
} else {
// It's empty for now, so let's say first that it's a string
row[index[j]] = detailed_datas[i][j];
}
}
}
formated_datas.push(row);
}
console.log(formated_datas); // #TODO : remove this
return formated_datas;
}
I transpile and resume Wetteren's code:
convertTSVtoJSON(tsvData) {
const formattedData = tsvData.split(/\r\n|\r|\n/g).filter(e => !!e).map((parsedEntry) => parsedEntry.split("\t"));
const tsvHeaders = formattedData.shift();
return formattedData.map(formattedEntry => {
{
return tsvHeaders.reduce((jsonObject, heading, position) => {
jsonObject[heading] = formattedEntry[position];
return jsonObject;
}, {});
}
});
}