JSON data to React Table - json

I am reading a Excel File as json objects.
Here is my Excel File.
I am reading excel data as json objects in the Inspect Tools as below.
I need to pass these json objects into a react table which can be selcted as row by row.
Is there any method to do this?

Since the excel data is shown in the inspect tools, we can set the data into the state and directly call them in the table.
handleFiles = event => {
var fileType = "xlsx";
if (event.target.files && event.target.files[0]) {
var extension = event.target.files[0].name
.split(".")
.pop()
.toLowerCase(), //file extension from input file
isSuccess = fileType.indexOf(extension) > -1; //is extension in acceptable types
if (isSuccess) {
//yes
var reader = new FileReader();
reader.onload = event => {
alert("Valid File extension");
const bstr = event.target.result;
const wb = XLSX.read(bstr, { type: "binary" });
console.log("data>>>", wb);
/* Get first worksheet */
const wsname = wb.SheetNames[0];
const ws = wb.Sheets[wsname];
/* Convert array of arrays */
const data = XLSX.utils.sheet_to_json(ws);
//set data into
this.setState({
data: XLSX.utils.sheet_to_json(ws)
});
// ws;
// { header: 1 }
// );
/* Update state */
console.log("Data>>>", data);
};
reader.readAsBinaryString(event.target.files[0]);
} else {
//no
alert("Invalid File Type ");
}
}
};
In the table it should be updated as below.
<CheckboxTable
.............
data={this.state.data}
........
/>

To iterate over object you can do this,
const data = Object.keys(obj).forEach(function(key,index) {
// key: the name of the object key
// index: the ordinal position of the key within the object
return (<tr><td>{obj[key]}</td>... //create td's as per your data</tr>)
});
In your component.
<Table>
{data}
</Table>

Related

Using setState but re-rendering is not executed?

I have this script, attr is hash object to keep application data.
const [attr,setAttr] = useState()
const onSetAttr = (data) =>{
console.log(data);
var new_attr = attr;
for (let key in new_attr) {
if (key in data){
new_attr[key] = data[key];
}
}
setAttr(new_attr);
console.log(new_attr);
}
It means the data and attr_should be marged as hash.
However setAttr works well but component is not re-rendered.
I google around and found this is related with imutable/mutable.
However in this case, how can i re-rendering forcebly?
You're mutating the same object, so reconciliation doesn't work properly. You should create a new one:
const [attr,setAttr] = useState()
const onSetAttr = (data) =>{
var new_attr = {...attr}; // <= object destructuring creates a new object
for (let key in new_attr) {
if (key in data){
new_attr[key] = data[key];
}
}
setAttr(new_attr);
console.log(new_attr);
}

Using a service in Jhipster to populate a second entity with user uploaded CSV BLOB entity

I am new to Jhipster and trying to create a basic app that will allow a user to upload a CSV file and then view the contents in an entity.
I am trying to figure out a way to populate a second entity with the data contained in a CSV blob that will be uploaded by the user. I have created an entity that allows the user to upload a CSV file and store it in the database as a BLOB, and I have also created a service with the intention of populating a second entity with records based on the contents of the CSV file that was uploaded.
How would I go about this? I have used OpenCSV in the past to read CSV files and populate MySQL tables via their filepath, but I am unfamiliar with accessing CSV files that are stored in the database as a BLOB.
I implemented same use case using supercsv but I don't store the csv in blob: in service I parse the DTO from controller and stores resulting entities, in the blob I store the errors if any. It's a bit abusive but it works well and the entity to create the other one is just a way to record how upload went, this way I can reuse the UI generated by JHipster without any change.
1.in html:
</td>
<td style="padding: 5px;">
<input type="button"
name="Reset"
id="txtFileReset"
class="btn btn-primary"
(click)="csvReset()"
value="Reset"/>
<input type="button"
name="Reset"
id="txtFileSave"
class="btn btn-primary"
(click)="csvSave()"
value="Save CSV To DB"/>
</td>
2.in ts:
csvRecords = [];
fileChangeListener($event): void {
const text = [];
const target = $event.target || $event.srcElement;
const files = target.files;
if (Constants.validateHeaderAndRecordLengthFlag) {
if (!this.fileUtil.isCSVFile(files[0])) {
alert('Please import valid .csv file.');
this.csvReset();
}
}
const input = $event.target;
const reader = new FileReader();
reader.readAsText(input.files[0]);
reader.onload = data => {
const csvData = reader.result;
const csvRecordsArray = csvData.split(/\r\n|\n/);
let headerLength = -1;
if (Constants.isHeaderPresentFlag) {
const headersRow = this.fileUtil.getHeaderArray(csvRecordsArray, Constants.tokenDelimeter);
headerLength = headersRow.length;
}
this.csvRecords = this.fileUtil.getDataRecordsArrayFromCSVFile(
csvRecordsArray,
headerLength,
Constants.validateHeaderAndRecordLengthFlag,
Constants.tokenDelimeter
);
if (this.csvRecords === null) {
// If control reached here it means csv file contains error, reset file.
this.csvReset();
}
};
reader.onerror = function() {
alert('Unable to read ' + input.files[0]);
};
}
csvReset() {
this.elementRef.nativeElement.querySelector('#txtFileUpload').value = '';
this.csvRecords = [];
}
csvSave() {
this.ipInfo = new IpInfoSdmSuffix();
for (let i = 1; i < this.csvRecords.length; i++) {
this.ipInfo.name = this.csvRecords[i][0];
this.ipInfo.addressStart = this.csvRecords[i][1];
this.ipInfo.addressEnd = this.csvRecords[i][2];
this.ipInfo.validType = this.csvRecords[i][3];
this.subscribeToSaveResponse(this.ipInfoService.create(this.ipInfo));
}
}
private subscribeToSaveResponse(result: Observable<HttpResponse<IIpInfoSdmSuffix>>) {
result.subscribe((res: HttpResponse<IIpInfoSdmSuffix>) => this.onSaveSuccess(), (res: HttpErrorResponse) => this.onSaveError());
}
private onSaveSuccess() {
this.isSaving = false;
this.isCsvSaved = false;
// this.previousState();
this.clear();
}
private onSaveError() {
this.isSaving = false;
this.isCsvSaved = false;
}

Convert .txt file to JSON

I want to convert a fairly unorganized and unstructured text file to JSON format. I want to be able to use the city ID information. Is there anyway I can convert this to JSON?
UPDATE: I also found this solution after a while. Very simple way to get the JSON of any tab separated text file.
https://shancarter.github.io/mr-data-converter/
You can try to use tsv2json this tool can reads a tsv file from stdin and writes a json file to stdout.
It's distributed in source file, to compile it you need to download D compiler and then run dmd tsv2json.d.
If you have more complex task there is another tool named tsv-utils
TSV to JSON in nodejs
var file_name = 'city_list.txt';
var readline = require('readline');
var fs = require('fs');
var lineReader = readline.createInterface({
input: fs.createReadStream(file_name)
});
var isHeader = false;
var columnNames = [];
function parseLine(line) {
return line.trim().split('\t')
}
function createRowObject(values) {
var rowObject = {};
columnNames.forEach((value,index) => {
rowObject[value] = values[index];
});
return rowObject;
}
var json = {};
json[file_name] = [];
lineReader.on('line', function (line) {
if(!isHeader) {
columnNames = parseLine(line);
isHeader = true;
} else {
json[file_name].push(createRowObject(parseLine(line)));
}
});
lineReader.on('close', function () {
fs.writeFileSync(file_name + '.json', JSON.stringify(json,null,2));
});

How to create an object of specific type from JSON in Parse

I have a Cloud Code script that pulls some JSON from a service. That JSON includes an array of objects. I want to save those to Parse, but using a specific Parse class. How can I do it?
Here's my code.
Parse.Cloud.httpRequest({
url: 'http://myservicehost.com',
headers: {
'Authorization': 'XXX'
},
success: function(httpResponse) {
console.log("Success!");
var json = JSON.parse(httpResponse.text);
var recipes = json.results;
for(int i=0; i<recipes.length; i++) {
var Recipe = Parse.Object.extend("Recipe");
var recipeFromJSON = recipes[i];
// how do i save recipeFromJSON into Recipe without setting all the fields one by one?
}
}
});
I think I got it working. You need to set the className property in the JSON data object to your class name. (Found it in the source code) But I did only try this on the client side though.
for(int i=0; i<recipes.length; i++) {
var recipeFromJSON = recipes[i];
recipeFromJSON.className = "Recipe";
var recipeParseObject = Parse.Object.fromJSON(recipeFromJSON);
// do stuff with recipeParseObject
}
Example from this page https://parse.com/docs/js/guide
var GameScore = Parse.Object.extend("GameScore");
var gameScore = new GameScore();
gameScore.save({
score: 1337,
playerName: "Sean Plott",
cheatMode: false
}, {
success: function(gameScore) {
// The object was saved successfully.
},
error: function(gameScore, error) {
// The save failed.
// error is a Parse.Error with an error code and message.
}
});
IHMO this question is not a duplicate of How to use Parse.Object fromJSON? [duplicate]
In this question the JSON has not been generated by the Parse.Object.toJSON function itself, but comes from another service.
const object = new Parse.Object('MyClass')
const asJson = object.toJSON();
// asJson.className = 'MyClass';
Parse.Object.fromJSON(asJson);
// Without L3 this results into:
// Error: Cannot create an object without a className
// It makes no sense (to me) why the Parse.Object.toJSON is not reversible

HTML FileReader

function fileSelected() {
// get selected file element
var files = document.getElementById('files[]').files;
for (var i = 0; i < files.length; i++) //for multiple files
{
(function (file) {
var fileObj = {
Size: bytesToSize(file.size),
Type: file.type,
Name: file.name,
Data: null
};
var reader = new window.FileReader();
reader.onload = function (e) {
fileObj.Data = e.target.result;
};
// read selected file as DataURL
reader.readAsDataURL(file);
//Create Item
CreateFileUploadItem(fileObj);
})(files[i]);
}
}
function CreateFileUploadItem (item) {
console.log(item);
$('<li>', {
"class": item.Type,
"data-file": item.Data,
"html": item.Name + ' ' + item.Size
}).appendTo($('#filesForUpload'));
}
So when console.log(item) gets run in the CreateFileUploadItem function it shows the item.Data. YET it won't add it to the data-file of the LI. Why is that?
The call to readAsDataURL is asynchronous. Thus, the function call is likely returning prior to the onload function being called. So, the value of fileObj.Data is still null when you are attempting to use it in CreateFileUploadItem.
To fix it, you should move the call to CreateFileUploadItem into your onload function. As for the console logging the proper value, you can't rely on that being synchronous either. I think using a breakpoint during debugging at that line instead will likely show the true null value.