Programs with Javascript json parsing - javascript

I am trying to parse a json object and try to do an alert in js if a particular word is detected in the json string,
CloudPush.addEventListener('callback', function (evt) {
//alert(evt);
alert(evt.payload);
var jsonNotification = JSON.parse(evt.payload);
for (var i = 0; i < jsonNotification.length; i++) {
var text = new String(jsonNotification[i]);
if (text == 'Hello') {
alert('Hello');
}else{
alert('Error');
}
}
I am however getting some errors that the alert 'Hello' does not display. Not really sure if I am doing it correctly. Hopefully someone can shed some light.

CloudPush.addEventListener('callback',
function (evt) {
// parse the desired data
var data= JSON.parse(evt.payload),
key;
// loop over all the keys of the JSON object
for (key in data) {
if(data.hasOwnProperty(key)){
alert( data[key] === 'Hello' ? 'Hello' : 'Error' );
}
}
);

Related

Uncaught TypeError: Cannot use ‘in’ operator to search for ‘length’ in jquery-1.11.1.js:583

I have two JS files as shown below (page1.js) and (page2.js for reference included below). I am basically referring to the following JSON response while working :
{
"webservice_status": {
"status": "SUCCESS",
"message": ""
},
"my_document_list": [{
"doc1": "445",
"doc2": "445",
"doc3": "445",
"doc4": "445",
"content": "Some text here to display"
}
]
}
Here is my page1.js related work:
$("#mydoclist").on('rowclick', function (event) {
row = event.args.rowindex;
datarow = $("#mydoclist").jqxGrid('getrowdata', row);
var response = JSON.stringify(datarow, null, 10);
var docID = datarow["doc_id"];
self.getMyDocumentContents(docID);
});
this.getMyDocumentContents = function (contentID_) {
var data = {
doc_id: contentID_
}
app_.get(data, self.processContent, app_.processError, url_name);
}// End of getMyDocumentContents
this.processContent = function(data_,textStatus_,jqXHR_) {
data_ = app_.convertResponse(data_,jqXHR_);
console.log("Checking for actual data_ content:", data_);
console.log("Actual Data Length Check for data_ content:", data_.my_document_list.length);
// debugger;
var collection = data_.my_document_list.length[0].content;
console.log("Collection Check",collection);
//debugger;
var source = {
localdata: collection,
datafields: [{
name: 'content',
type: 'string'
}],
datatype: "array"
};
var dataAdapter = new $.jqx.dataAdapter(source, {
loadComplete: function (records) {
debugger;
var html;
//Get data
var records = dataAdapter.records;
console.log("Check for records:",records.length);
var length = records.length;
html = "<div style='margin: 10px;'><pre>" + records[0].content + "</pre></div>";
$("#docContentPanel").jqxPanel('clearcontent');
$("#docContentPanel").jqxPanel('append',html);
},
loadError: function (xhr, status, error) { },
beforeLoadComplete: function (records) {
}
});
// perform data binding
dataAdapter.dataBind();
var panel = $("#docContentPanel");
var content = panel.html();
panel.jqxPanel({ width: '750', height: '500', scrollBarSize: 20 });
}// End of processContent
Here is my page2.js related work:
this.get = function (data_, done_, fail_, webServiceKey_) {
// Lookup the requested web service URL
var url = https://documentlookup.com:8443/getmydocuments;
// Create the AJAX request.
$_.ajax({
data: data_,
method: "GET",
url: url
})
.success(done_)
.error(fail_);
};
// If the JSON data was returned with content type of "text/plain", parse as JSON before returning.
this.convertResponse = function (data_, jqXHR_) {
return (typeof(data_) === "object" ? data_ : JSON.parse(data_));
};
Basically there is a list of rows displayed in a jqxgrid(not mentioned in the code above), when a user clicks on it
$("#mydoclist").on('rowclick gets called , which calls the following function:
getMyDocumentContents function: This function basically passes the doc_id inside data variable which is made
available for the following function:
processContent:
In this function, I am trying to show in jqxPanel the value of the contentwhich is in my_document_list array.
Problem I am facing inside this function:
As can be seen, there are debugger I placed at various places which are currently commented except at one place
which is just below this line loadComplete: function (records) {
I don’t get any error above this line var dataAdapter = new $.jqx.dataAdapter(source, { , however, as soon as
I place it inside it, I get the following error:
Uncaught TypeError: Cannot use ‘in’ operator to search for ‘length’ in jquery-1.11.1.js:583
Where length is a numerical number which keeps on changing depending upon the length of value of content in the above JSON response.
Could anyone tell me what’s going wrong? thanks in advance !
Just in case needed, here is the jQuery line #583 isArraylike function :
function isArraylike( obj ) {
var length = obj.length,
type = jQuery.type( obj );
if ( type === "function" || jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj; // THIS is LINE 583 which throws error
}
Should I try changing the jQuery version?
At data_.my_document_list.length[0].content; I think you need data_.my_document_list[0].content;.
my_document_list is an array and as such the array access should occur there.

Array value becomes null while passing from Ajax

I am making an ajax call in my javascript submit function. In this ajax call, I am passing an array(globalSelection) as data to the servlet. This array consists elements of function textSelection which is also pasted below.
globalSelection =[];
function submit() {
console.log("globalSelection start")
console.log(globalSelection)
console.log("globalSelection end")
$.ajax({
async : false,
type : "POST",
url : 'http://example.com:8080/myApp/DataServlet',
data: {globalSelection:globalSelection},
success : function(data) {
alert(data)
},
error : function(data, status, er) {
alert("error: " + data + " status: " + status + " er:" + er);
}
});
}
function textSelection(range, anchorNode, focusNode) {
this.range = range;
this.type = 3;
this.rCollection = [];
this.textContent = encodeURI(range.toString());
this.anchorNode = anchorNode;
this.focusNode = focusNode;
this.selectionId = getRandom();
this.yPOS = getYPOS();
this.getTagName = function(range) {
var el = range.startContainer.parentNode;
return el;
}
this.getTagIndex = function(el) {
var index = $(el.tagName).index(el);
return index;
}
this.simpleText = function(node, range) {
if (!node)
var entry = this.createEntry(this.anchorNode, this.range);
else
var entry = this.createEntry(node, range);
this.rCollection.push(entry);
this.highlight(this.rCollection[0].range);
this.crossIndexCalc();
textSelection._t_list.push(this);
pushto_G_FactualEntry(this);
}
this.compositeText = function() {
this.findSelectionDirection();
var flag = this.splitRanges(this.anchorNode, this.focusNode,
this.range.startOffset, this.range.endOffset);
if (flag == 0) {
for (j in this.rCollection) {
this.highlight(this.rCollection[j].range);
}
}
this.crossIndexCalc();
textSelection._t_list.push(this);
pushto_G_FactualEntry(this);
}
}
I am ading the screen of my browser console below, which prints the globalSelection(array).
In my servlet I am getting this array as follows
String[] arrays = request.getParameterValues("globalSelection[]");
System.out.println(arrays);
Here I am getting null value for arrays.
If I put globalSelection as follows in submit function for simple test to servlet, I am able to get the arrays.
var globalSelection = ["lynk_url", "jsonBody", "lynk_dummy1", "lynk_dummy2", "lynk_name", "lynk_desc", "lynk_flag"];
Why my actual globalSelection is shows null in servlet, what I am doing wrong here.
Try with :
String[] arrays = request.getParameterValues("globalSelection");
System.out.println(arrays);
Because the parameter submitted with name "globalSelection" only not "[]" symbol.
I see your problem and I have a simple solution.
I recommend in that case that you convert the array as a string in JS:
JSON.stringify(globalSelection)
and then reconstructing the object on the backend using some sort of library for JSON conversion like: https://code.google.com/archive/p/json-simple/
You could then do something like this:
JSONArray globalSelection = (JSONArray) new JSONParser().parse(request.getParameter("globalSelection"));
Iterator i = globalSelection.iterator();
while (i.hasNext()) {
JSONObject selection = (JSONObject) i.next();
String type = (String)selection.get("type");
System.out.println(type);
}
This will parse your array and print the selection type. Try it, hope it helps.

get object data , load 2 condition the same time

var id = "displayImage1";
//my object
var json = {
displayImage1: {
object: "style1"
},
displayImage2: {
object: "style2"
},
displayImage3: {
object: "style3"
}
};
function JsonLoad(_id){
checkImgCanvas = _id;
for (var i in json) {
if(i === checkImgCanvas){
alert("yes got it");
}else{
alert("not object found");
}
}
}
i am using this function to check if any json object value match the id value , if yes load "yes got it" else load "not object found". i do get the match but it also load "not object found" 2 times , i have no idea why ? it should not load the else condition cause i have match in my json object.
how do i make this function if match load "yes" if no load else condition.(load once)
Demo
Since your for loop executes even after you found your result, you are getting the "no object found" message. You should exit your loop once you found your desired result and to achieve that, you can use break; after your success alert message
function JsonLoad(_id){
var matchFound = false;
for (var i in json) {
if(i === _id) {
matchFound = true;
break;
}
}
if(matchFound) {
alert("yes got it");
}else{
alert("not object found");
}
}
You can use Array.prototype.some()
The some() method tests whether some element in the array passes the test implemented by the provided function.
var json = { displayImage1: { object: "style1" }, displayImage2: { object: "style2" }, displayImage3: { object: "style3" } };
function JsonLoad(_id) {
!Object.keys(json).some(function (k) {
if (k === _id) {
document.write('yes got it<br>')
return true;
}
}) && document.write('not object found<br>');
}
JsonLoad('displayImage0');
JsonLoad('displayImage1');

Displaying JSON data in Javascript loop

I am having an issue displaying json data. I have searched and found many examples, but for some reason I get the "Cannot read property 'length' of undefined" error, because "var object = notes.data;" comes back as undefined.
Why is object undefined? From everything I can see I am doing it right.
My json that is returned.
{
"data":[
{
"NumberOfAnswers":25,
"Answer":"51-89 Percent of all items in section are <b>IN STOCK<\/b>",
"Percent":54.35
},
{
"NumberOfAnswers":21,
"Answer":"90-100 Percent of all items in section are <b>IN STOCK<\/b>",
"Percent":45.65
}
]
}
And here is the function to display it. (With some debugging code as well)
function format(notes) {
console.log(notes); //this displays the json
var object = notes.data;
console.log(object);
var i;
for (var i = 0; i < object.length; i++) {
var Result = object[i];
var Answer = Result.Answer;
console.log(Answer)
}
}
Here is the ajax function:
$.ajax({
type: 'post',
url: '/rmsicorp/clientsite/pacingModal/surveyajax2.php',
success: function(result) {
if (row.child.isShown()) {
row.child.hide();
tr.removeClass('shown');
detailsrows.splice(RowID, 1);
} else {
row.child(format(result)).show();
tr.addClass('shown');
if (RowID === -1) {
detailsrows.push(tr.attr('id'));
}
}
}
});
Most likely, the response is still in string format. You can add JSON.parse to convert it to an object and then be able too access the data property.
Try modifying your function like this to see if it fixes the problem.
function format(notes) {
console.log(notes); //this displays the json
// The following converts the response to a javascript object
// and catches the exception if the response is not valid JSON
try {
notes = JSON.parse(notes);
} catch(e) {
console.log('notes is not valid JSON: ' + e);
}
var object = notes.data;
console.log(object);
var i;
for (var i = 0; i < object.length; i++) {
var Result = object[i];
var Answer = Result.Answer;
console.log(Answer)
}
}

How to check if it's a string or json [duplicate]

This question already has answers here:
How to test if a string is JSON or not?
(22 answers)
Closed 3 years ago.
I have a json string that is converted from object by JSON.Stringify function.
I'd like to know if it's json string or just a regular string.
Is there any function like "isJson()" to check if it's json or not?
I'd like to use the function when I use local storage like the code below.
Thank you in advance!!
var Storage = function(){}
Storage.prototype = {
setStorage: function(key, data){
if(typeof data == 'object'){
data = JSON.stringify(data);
localStorage.setItem(key, data);
} else {
localStorage.setItem(key, data);
}
},
getStorage: function(key){
var data = localStorage.getItem(key);
if(isJson(data){ // is there any function to check if the argument is json or string?
data = JSON.parse(data);
return data;
} else {
return data;
}
}
}
var storage = new Storage();
storage.setStorage('test', {x:'x', y:'y'});
console.log(storage.getStorage('test'));
The "easy" way is to try parsing and return the unparsed string on failure:
var data = localStorage[key];
try {return JSON.parse(data);}
catch(e) {return data;}
you can easily make one using JSON.parse. When it receives a not valid JSON string it throws an exception.
function isJSON(data) {
var ret = true;
try {
JSON.parse(data);
}catch(e) {
ret = false;
}
return ret;
}
Found this in another post How do you know if an object is JSON in javascript?
function isJSON(data) {
var isJson = false
try {
// this works with JSON string and JSON object, not sure about others
var json = $.parseJSON(data);
isJson = typeof json === 'object' ;
} catch (ex) {
console.error('data is not JSON');
}
return isJson;
}
Since the question is "How to check if it's a string or json" maybe a simple way would be to check for string, so you would have done something like this somewhere:
if (typeof data === 'string') { // check for string!
//... do something
} else {///... do something else}
Maybe that could be enough depending on your overall solution, just in case someone else is looking around.
I think returning parsed JSON at the same time is a good idea, so I prefer following version:
function tryParse(str) {
try {
return { value: JSON.parse(str), isValid: true }
} catch (e) {
return { value: str, isValid: false }
}
}
As you probably know JSON.parse("1234"), JSON.parse("0"), JSON.parse("false") and JSON.parse("null") won't raise Exception and will return true. all this values are valid JSON but if you want to see isValid is true only for objects (e.g: { "key": "value" }) and arrays (e.g: [{ "key": "value" }]) you can use following version:
function tryParse(str) {
try {
var parsed = JSON.parse(str);
return { value: parsed , isValid: typeof parsed === 'object'}
} catch (e) {
return { value: str, isValid: false }
}
}

Categories