Unable to store and retrieve JSON value by JQUERY - json

I have two textbox(goalText and goalText1) and a button(goalreach) in my html.
My aim : When I enter numeric value in 1 textbox(goalText), it should be converted to json and be stored. So even after 5 days when I run the application, it should be stored. Now when I enter the numeric value, in other textbox(goalText1) and it matches, I am simply displaying the message match. This is the demo, I am trying so that I can know that value can be stored in json and can be retrieved when necessary. I have written the code as follow:
$("#goalreach").click(function () {
var contact = new Object();
contact.goalDist = "$("#goalText.value ").val()";
var jsonText = JSON.stringify(contact);
if (jsonText == ($("#goalText1.value").val())) {
document.getElementById('divid').innerHTML = 'Match';
}
});
I know, I have made many simple mistakes of brackets and " too, but I am a newbie, If you can help me out.

First, you have to compare either 2 objects or 2 strings, and in goalDist, you should store the value (BTW, you get the jQuery object with $("#goalText") and the value with somejQueryObject.val() moreover this is generally equivalent to document.getElementById("goalText").value)...
This can be done like this :
$("#goalreach").click(function () {
// Create an object with the single property "goalDist"
var contact = { goalDist : $("#goalText").val() };
// Makes it be a string (it will in this simple example : `"{"goalDist":<the value of goalTest>}"`
var jsonText = JSON.stringify(contact);
// Creates a string from an equivalent object bound on the second field
var jsonText2 = JSON.stringify({ goalDist : $("#goalText2").val() });
// Compares the 2 strings
if (jsonText === jsonText2) {
document.getElementById('divid').innerHTML = 'Match';
}
});

TRY THIS
$("#goalreach").click(function () {
var contact = new Object();
var goalDist = '$("#goalText.value").val()';
var jsonText = JSON.stringify(contact.goalDist);
if(jsonText==($("#goalText1.value").val()))
{
document.getElementById('divid').innerHTML = 'Match';
}
});

Try the following code:
$("#goalreach").click(function () {
var contact = new Object();
contact.goalDist = $("#goalText").val();
var jsonText = JSON.stringify(contact);
if (jsonText == ($("#goalText1").val())) {
document.getElementById('divid').innerHTML = 'Match';
}
});
OR
$("#goalreach").click(function () {
var goalText = $("#goalText").val();
var goalText1 = $("#goalText1").val();
if (goalText == goalText1) {
document.getElementById('divid').innerHTML = 'Match';
}
});

Related

How do I change the return format of Slate queries from column to row?

The results of my query look like:
{
col1: [values],
col2: [values]
}
Is there a way to get my query to return as a list of rows objects?
The best way is to write a function to convert your query response.
One example:
function transformColumnSchemaToRowSchema(data) {
var keys = _.keys(data);
var arrays = _.values(data);
var arrayOfPropertyLists = _.zip.apply(_, arrays);
var arrayOfObjects = _.map(arrayOfPropertyLists, function(list) {
var obj = {};
_.each(keys, function(key, i) {
obj[key] = list[i];
});
return obj;
});
return arrayOfObjects;
}
Or a more compact version:
var data = {{q_some_query}};
delete data['_response']
var newdata = _.zip.apply(_, _.values(data)).map((val) => _.zipObject(_.keys(data), val));
After you convert to this format, you might want to convert back to the original format (for example, if you want to put the data into a table widget in Slate). This is how that can be done:
var original_fmt = {};
_.forEach(_.keys(newdata[0]), function(k) {
original_fmt[k] = _.map(newdata, k);
});
// use original_fmt

Angular 2 - Parsing Excel worksheet to 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);

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)

Extjs: how to use object key value with space in extjs tpl?

CODE :
var data={"today date":'12-02-2014' ,"created date":'10-2-1014'}
tpl= new Ext.XTemplate('<tpl for=".">','<p>{today date}</p>','<p>{created date}</p>','</tpl>');
here I have attached the sample code.
Simple answer: don't.
var data = {"today date":'12-02-2014' ,"created date":'10-2-1014'};
// notice udpated variable names
var tpl = new Ext.XTemplate('<tpl for=".">','<p>{today_date}</p>','<p>{created_date}</p>','</tpl>');
var fixedData = {};
Ext.each(Ext.Object.getKeys(data), function(key) {
fixedData[key.replace(/ /g, '_')] = data[key];
});
// test
alert(tpl.apply(fixedData));