Angular 2 - Parsing Excel worksheet to Json - json

I have an Excel file with the following content:
Inside my component.ts, I extract the Excel's content as follow:
var testUrl= "excel.xlsx";
var oReq = new XMLHttpRequest();
oReq.open("GET", testUrl, true);
oReq.responseType = "arraybuffer";
oReq.onload = function(e) {
var arraybuffer = oReq.response;
var data = new Uint8Array(arraybuffer);
var arr = new Array();
for(var i = 0; i != data.length; ++i){
arr[i] = String.fromCharCode(data[i]);
}
var bstr = arr.join("");
var workbook = XLSX.read(bstr, {type:"binary"});
var first_sheet_name = workbook.SheetNames[0];
var worksheet = workbook.Sheets[first_sheet_name];
var json = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]], {header:1, raw:true});
var jsonOut = JSON.stringify(json);
console.log("test"+jsonOut);
}
oReq.onerror = function(e) {
console.log(e);
}
oReq.send();
XLSX.utils.sheet_to_json will format JSON as follow:
However, I would like the JSON to be as follow:
Most probably I would need to manually create the JSON, but can anyone help me point to the direction on how I can accomplish this?

In your case we need to modify the JSON data by looping over XLSX.utils.sheet_to_json JSON object:
// This object will contain the data in the format we want
var finalObj = { "object": []};
// Variables to track where to insert the data
var locIndex, firstCondIndex, secondCondIndex,
lockey, firstCondKey, secondCondkey;
// We need to initialize all indexes to -1 so that on first time we can get 0, as arrays start with 0 in javascript
locIndex = -1;
// here obj is XLSX.utils.sheet_to_json
obj.object.map((value, index) => {
// we don't want to consider name of columns which is first element of array
if(!index) return;
// Go inside only if not null
if(value[0]) {
// For Location
finalObj.object.push(createObj(value[0]));
locIndex++;
// We also need to store key names to push it's children
lockey = value[0];
firstCondIndex = -1;
}
if(value[1]) {
// For First Condition
finalObj.object[locIndex][lockey].push(createObj(value[1]));
firstCondIndex++;
firstCondKey = value[1];
secondCondIndex = -1;
}
if(value[2]) {
// For Second Condition
finalObj.object[locIndex][lockey][firstCondIndex][firstCondKey].push(createObj(value[2]));
secondCondIndex++;
secondCondkey = value[2];
}
if(value[3]) {
// For Products
// We just push the string
finalObj.object[locIndex][lockey][firstCondIndex][firstCondKey][secondCondIndex][secondCondkey].push(value[3]);
}
});
function createObj(val) {
// We need to initialize blank array so we can push the children of that element later on
var obj = {};
obj[val] = [];
return obj;
}
console.log(finalObj);

Related

How to create Mesh based on a JSON-Object in three.js

I have an ajax request which helps me to get a JSON-object from a webserver!
function _loadModel(filename) {
var request = new XMLHttpRequest();
request.open("GET", filename);//open(method, url, async)
request.onreadystatechange = function() {
console.info(request.readyState +' - '+request.status);
if (request.readyState == 4) {//4 == finished download
if(request.status == 200) { //OK -> bezogen auf http Spezifikation
handleLoadedGeometry(filename,JSON.parse(request.responseText));
}
else if (document.domain.length == 0 && request.status == 0){ //OK but local, no web server
handleLoadedGeometry(filename,JSON.parse(request.responseText));
}
else{
alert ('There was a problem loading the file :' + filename);
alert ('HTML error code: ' + request.status);
}
}
}
request.send();// send request to the server (used for GET)
}
_loadModel('http://localhost:8080/bbox?XMIN=3500060&YMIN=5392691&XMAX=3500277&YMAX=5393413')
JSON file:
[{"building_nr": 5, "geometry": "{\"type\":\"Polygon\",\"coordinates\":[[[3500267.16,5392933.95,456.904],[3500259.19,5392933.01,456.904],[3500258.586,5392938.152,456.904],[3500258.02,5392942.97,456.904],[3500265.98,5392943.94,456.904],[3500266.552,5392939.097,456.904],[3500267.16,5392933.95,456.904]]]}", "polygon_typ": "BuildingGroundSurface"}, ...]
This is one object and I have a lot of them in this array.
Now I want to create a mesh!
I think this can be done inside the function handleLoadedGeometry()
//Callback funktion
function handleLoadedGeometry(filename, model) {
var geom = new THREE.BufferGeometry();
for (var i=0;i<10;i++)
{
var vertex = new THREE.Vector3();
vertex.x = model.geometry[i].coordinates[0];
vertex.y = model.geometry[i].coordinates[1];
vertex.z = model.geometry[i].coordinates[2];
geometry.vertices.push( vertex );
}
geom.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
var material = new THREE.MeshBasicMaterial( { color: 0xff00f0 } );
var mesh = new THREE.Mesh( geom, material );
Scene.scene.add(mesh);
}
At the end I get this error in the browser: Cannot read property '0' of undefined
How can I refer to geometry coordinates inside the JSON?
from what you provided it seems the loaded JSON contains an array of multiple objects that is why you get the error
try something like this
function handleLoadedGeometry(filename, models) {
for (var i=0; i<models.length; i++)
{
var model = models[i];
var coordinates = model.geometry.coordinates;
var positions = [];
for (var j=0; j<coordinates.length; j++){
positions.push(coordinates[j][0]);
positions.push(coordinates[j][1]);
positions.push(coordinates[j][2]);
}
var geometry = new THREE.BufferGeometry();
// buffer attributes contain an array not vectors
var positionAttribute = new THREE.BufferAttribute(new Float32Array(positions),3);
geometry.addAttribute("position", positionAttribute);
var material = new THREE.MeshBasicMaterial( { color: 0xff00f0 } );
var mesh = new THREE.Mesh( geom, material );
Scene.scene.add(mesh);
}
}
or remove the first loop if you call it for each object in the JSON array
I did it in another way...I just created instead of BufferGeometry the default Geometry in three.js:
function handleLoadedGeometry(filename) {
var material = new THREE.MeshBasicMaterial({color: 0xFF0000});
for (var i=0; i<filename.length; i++)
{
var model = filename[i]; // erstes Objekt
var coordinates = JSON.parse(model.geometry);
var geometry = new THREE.Geometry();
var coordinates_updated = _transformCoordinates(coordinates.coordinates[0]);
for (var j = 0; j<coordinates_updated.vertices.length; j++){
geometry.vertices.push(
//new THREE.Vector3(coordinates.coordinates[0][j][0], coordinates.coordinates[0][j][1], coordinates.coordinates[0][j][2])//x,y,z Koordinatenpunkte für Surface 1
new THREE.Vector3(coordinates_updated.vertices[j][0],coordinates_updated.vertices[j][1],coordinates_updated.vertices[j][2])
);
geometry.faces.push(
new THREE.Face3(0,1,2),
new THREE.Face3(0,3,2)
geometry.computeBoundingSphere();
}
var mesh = new THREE.Mesh(geometry, material);
Scene.scene.add(mesh);
}
};
And now it works!
I think BufferGeometry is more for more complex surfaces.

Convert a javascript array to specific json format

I have this JSON.stringify(array) result: ["id:1x,price:150","id:2x,price:200"] and I have to convert it in a json format similar to this (it would be sent to php):
[{
"id":"1x",
"price":150
},
{
"id":"2x",
"price":200
}]
Please help.
You can convert the structure of your data before using JSON.stringify, for example you can convert the data to a list of objects like so:
var strItems = ["id:1x,price:150", "id:2x,price:200"];
var objItems = [];
for (var i = 0; i < strItems.length; i++) {
var pairs = strItems[i].split(",");
objItems.push({
id: pairs[0].split(':')[1],
price: parseInt(pairs[1].split(':')[1])
});
}
Before calling JSON.stringify to get the result you're after:
var json = JSON.stringify(objItems);
console.log(json);
JSON.stringify(array) only does on layer, but you can change the stringify function to work for multiple layers with this function written by JVE999 on this post:
(function(){
// Convert array to object
var convArrToObj = function(array){
var thisEleObj = new Object();
if(typeof array == "object"){
for(var i in array){
var thisEle = convArrToObj(array[i]);
thisEleObj[i] = thisEle;
}
}else {
thisEleObj = array;
}
return thisEleObj;
};
var oldJSONStringify = JSON.stringify;
JSON.stringify = function(input){
if(oldJSONStringify(input) == '[]')
return oldJSONStringify(convArrToObj(input));
else
return oldJSONStringify(input);
};
})();
Once you have declared this, then you can call JSON.stringify(array)

How to get nested deep property value from JSON where key is in a variable?

I want to bind my ng-model with JSON object nested key where my key is in a variable.
var data = {"course":{"sections":{"chapter_index":5}}};
var key = "course['sections']['chapter_index']"
Here I want to get value 5 from data JSON object.
I found the solution to convert "course.sections.chapter_index" to array notation like course['sections']['chapter_index'] this. but don't know how to extract value from data now
<script type="text/javascript">
var BRACKET_REGEXP = /^(.*)((?:\s*\[\s*\d+\s*\]\s*)|(?:\s*\[\s*"(?:[^"\\]|\\.)*"\s*\]\s*)|(?:\s*\[\s*'(?:[^'\\]|\\.)*'\s*\]\s*))(.*)$/;
var APOS_REGEXP = /'/g;
var DOT_REGEXP = /\./g;
var FUNC_REGEXP = /(\([^)]*\))?$/;
var preEval = function (path) {
var m = BRACKET_REGEXP.exec(path);
if (m) {
return (m[1] ? preEval(m[1]) : m[1]) + m[2] + (m[3] ? preEval(m[3]) : m[3]);
} else {
path = path.replace(APOS_REGEXP, '\\\'');
var parts = path.split(DOT_REGEXP);
var preparsed = [parts.shift()]; // first item must be var notation, thus skip
angular.forEach(parts, function (part) {
preparsed.push(part.replace(FUNC_REGEXP, '\']$1'));
});
return preparsed.join('[\'');
}
};
var data = {"course":{"sections":{"chapter_index":5}}};
var obj = preEval('course.sections.chapter_index');
console.log(obj);
</script>
Hope this also help others. I am near to close the solution,but don't know how can I get nested value from JSON.
This may be a good solution too
getDeepnestedValue(object: any, keys: string[]) {
keys.forEach((key: string) => {
object = object[key];
});
return object;
}
var jsonObject = {"address": {"line": {"line1": "","line2": ""}}};
var modelName = "address.line.line1";
var result = getDescendantPropValue(jsonObject, modelName);
function getDescendantPropValue(obj, modelName) {
console.log("modelName " + modelName);
var arr = modelName.split(".");
var val = obj;
for (var i = 0; i < arr.length; i++) {
val = val[arr[i]];
}
console.log("Val values final : " + JSON.stringify(val));
return val;
}
You are trying to combine 'dot notation' and 'bracket notation' to access properties in an object, which is generally not a good idea.
Source: "The Secret Life of Objects"
Here is an alternative.
var stringInput = 'course.sections.chapter_index'
var splitInput = stringInput.split(".")
data[splitInput[1]]][splitInput[2]][splitInput[3]] //5
//OR: Note that if you can construct the right string, you can also do this:
eval("data[splitInput[1]]][splitInput[2]][splitInput[3]]")
Essentially, if you use eval on a string, it'll evaluate a statement.
Now you just need to create the right string! You could use the above method, or tweak your current implementation and simply go
eval("data.course.sections.chapter_index") //5
Source MDN Eval docs.
var data = {
"course": {
"sections": {
"chapter_index": 5
}
}
};
var key = "course['sections']['chapter_index']";
var keys = key.replace(/'|]/g, '').split('[');
for (var i = 0; i < keys.length; i++) {
data = data[keys[i]];
}
console.log(data);
The simplest possible solution that will do what you want:
var data = {"course":{"sections":{"chapter_index":5}}};
var key = "course['sections']['chapter_index']";
with (data) {
var value = eval(key);
}
console.log(value);
//=> 5
Note that you should make sure key comes from a trusted source since it is eval'd.
Using with or eval is considered dangerous, and for a good reason, but this may be one of a few its legitimate use cases.
If you don't want to use eval you can do a one liner reduce:
var data = {"course":{"sections":{"chapter_index":5}}};
var key = "course['sections']['chapter_index']"
key.split(/"|'|\]|\.|\[/).reduce((s,c)=>c===""?s:s&&s[c], data)

How to pass a whole dojox.grid.DataGrid store(items json data) to servlet?

I have a button on page - when clicked, it passes all the data to the servlet that could update each row data. My question is how to pass the whole store to the servlet as json data? Is there any easy way? Thanks
Here is some code I wrote to get the store to an object. Then it can be converted to JSON using dojo.toJson(obj);. I learned about this from the dojotoolkit website originally. (Give credit where credit is due). I realize this code is huge and nasty. When I looked for a better way about a year back I could not find one.
JsonHelper.storeToObject = function(store) {
var object = [];
var index = -1;
store.fetch({
onItem : function(item, request) {
object[++index] = JsonHelper.itemToObject(store, item);
}
});
return object;
};
JsonHelper.itemToObject = function(store, item) {
// store:
// The datastore the item came from.
// item:
// The item in question.
var obj = {};
if (item && store) {
// Determine the attributes we need to process.
var attributes = store.getAttributes(item);
if (attributes && attributes.length > 0) {
var i;
for (i = 0; i < attributes.length; i++) {
var values = store.getValues(item, attributes[i]);
if (values) {
// Handle multivalued and single-valued attributes.
if (values.length > 1) {
var j;
obj[attributes[i]] = [];
for (j = 0; j < values.length; j++) {
var value = values[j];
// Check that the value isn't another item. If
// it is, process it as an item.
if (store.isItem(value)) {
obj[attributes[i]].push(itemToObject(store,
value));
} else {
obj[attributes[i]].push(value);
}
}
} else {
if (store.isItem(values[0])) {
obj[attributes[i]] = itemToObject(store,
values[0]);
} else {
obj[attributes[i]] = values[0];
}
}
}
}
}
}
return obj;
};

Read list from json object

I am try to read list from json here id my code:-
List<EmailProvider> list = new List<EmailProvider>();
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("~/WidgetXml.xml"));
XmlElement root = doc.DocumentElement;
XmlNodeList nodes = root.SelectNodes("//widget");
foreach (XmlNode node in nodes)
{
EmailProvider obj = new EmailProvider();
obj.Name = node["Name"].InnerText;
obj.left = Convert.ToInt32(node["left"].InnerText);
obj.Id = node["id"].InnerText;
obj.IsVisible = Convert.ToBoolean(node["isActive"].InnerText);
long s = Int64.Parse(node["top"].InnerText);
obj.top = s;
obj.desc = node["desc"].InnerText;
list.Add(obj);
}
var result = list.OrderBy(p => p.IsVisible).ToList();
return result.ToArray();
and on view:-
$(document).ready(function () {
$.post(siteUrl.getSiteUrl + '/Admin/ReadXml/', function (data) {
alert(data.length);
var st = JSON.stringify(data);
alert(st.length);
});
});
length always show 54 but in array only 4 items. How can i read all recors from array by json from json object.
Thanks in advance.
Try returning a JsonResult from your controller method, using the controller method Json
var result = list.OrderBy(p => p.IsVisible).ToList();
return Json(result.ToArray());
On JavaScript, you should just need to iterate over the array as in:
$(document).ready(function () {
$.post(siteUrl.getSiteUrl + '/Admin/ReadXml/', function (data) {
for(var i = 0;i < data.length; i++){
alert(data[i].Name);
}
});
});