JSON Parsing in AngularJS Service - javascript

I have Angular service and in that service I have a code:
this.testMethod = function( ) {
this.jsonTest = "[{'id':'123','title':'XYZ','id2':'456','status':2}]";
this.parseTest(this.jsonTest);
};
this.parseTest = function(jsonTest) {
var jsonTestObj = JSON.parse(jsonTest); // I get error hear
}
Test method is getting called on ng-click event.
Error that I am getting while testing in latest chrome browser:
SyntaxError: Unexpected token ' at Object.parse (native)
......
I tried multiple things to fix it but nothing seems to work.
Every time I get undefined value error.
Basically I want to parse JSON object and get the values.
What am I doing wrong?

Use this
this.jsonTest = '[{"id":"123","title":"XYZ","id2":"456","status": "2"}]';
Or this
this.jsonTest = "[{\"id\":\"123\",\"title\":\"XYZ\",\"id2\":\"456\",\"status\": \"2\"}]";
You either need to use ' outside or " outside and escape the quotes inside.
Both the key and value need to be in double quotes.

You need to use double quotes in your string, other than that your code should work.
To quote from specification
A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.

Your JSON is not valid. Always check your JSON integrity in those cases, i personaly use
http://jsonlint.com/

Related

Passing values from JavaServlet to Javascript, calling a Function in Javascript

So there is an old code base I am leveraging from work, currently they are sending over 2 items from an object and I'm adding a third. The third object I'm sending in JAVA as a string, however in the communication over to javascript it's freaking out, I'm getting a horrible error as prototype is declaring it undefined, however I'm watching the code being sent.
Currently the Java code is calling the function. Passing the following data over. All of these are strings.
setCCInfo(xxxxxxxxxxxxxx2205, 1219, 60W76W);
When I remove the final variable, and pass just the first two the function works, however it's almost like prototype is expecting a numeral as I had to change the other two into strings when it got to the front end. I'll attach the code below. The current Error I'm getting is
"prototype-1.6.0.2.js:394 Uncaught SyntaxError: Invalid or unexpected
token
at prototype-1.6.0.2.js:394
at prototype-1.6.0.2.js:635
at prototype-1.6.0.2.js:595
at Array.forEach ()
at Array.each (prototype-1.6.0.2.js:594)
at Array.collect (prototype-1.6.0.2.js:634)
at String.evalScripts (prototype-1.6.0.2.js:394)
at Function. (prototype-1.6.0.2.js:209)
at prototype-1.6.0.2.js:231"
ctx.getResponse().getWriter().print(output.getString("TCResultStatus").toUpperCase());
StringBuilder str = buildJavascriptCall(cceft);
ctx.getResponse().getWriter().print(str.toString());
private StringBuilder buildJavascriptCall(CcEft cceft) {
StringBuilder str = new StringBuilder();
str.append("<script type='text/javascript'>setCCInfo(");
str.append(cceft.getMaskedCCNum());
str.append(", ");
str.append(cceft.getCombinedExpDate());
str.append(", ");
str.append(cceft.getBillingId());
str.append(");</script>");
return str;
}

Saving and getting an array in Localstorage?

I am trying to save an array into localstorage and then get it.
localStorage.setItem("savedquestionslist", questions);
console.log(localStorage.getItem(savedquestionslist));
The variable 'questions' is an array.
However I get this error:
ReferenceError: savedquestionslist is not defined.
I still get the error even if I do this:
localStorage.setItem("savedquestionslist", "test");
console.log(localStorage.getItem(savedquestionslist));
Does anyone know what the issue is? Thanks
savedquestionslist needs to be a string.
console.log(localStorage.getItem('savedquestionslist'));
The problem is in your syntax for getItem.
It takes in a string as an argument. You are passing a variable and the error represents that the variable savedquestionslist is not defined.
Change your code to :
localStorage.setItem("savedquestionslist", questions);
console.log(localStorage.getItem("savedquestionslist"));
An example would be
var questions = ['firstQuestion', 'secondQuestion', 'thirdQuestion'];
localStorage.setItem("savedquestionslist", questions);
console.log(localStorage.getItem("savedquestionslist"));
The error you're getting is because you forgot the quotes in the getItem call:
console.log(localStorage.getItem("savedquestionslist"));
// ------------------------------^------------------^
Or you can use literal access:
console.log(localStorage.savedquestionslist);
But in both cases, since local storage only stores strings, I'd use JSON, since otherwise your array won't be saved / retrieved correctly:
localStorage.setItem("savedquestionslist", JSON.stringify(questions));
console.log(JSON.parse(localStorage.getItem("savedquestionslist")) || []);
(The || [] is for if you've never set the item, it provides a default of an empty array.)

access formatted value with special character in javascript array

I am getting an object as response for an api call
The object looks like below
Now when I try response._modifiedby_value I am getting the right response, but when I try response.createdby_value#OData.Community.Display.V1.FormattedValue I am getting the below error
Uncaught SyntaxError {message: "Unexpected token ILLEGAL"}
that's because '#' is a special character, therefore you can't do:
response.createdby_value#OData = 2;
but instead
response["createdby_value#OData"] = 2;

Javascript: String concatenation in object constructor

Been trying to create a JavaScript object member that always contains a common string. Whenever I create a new object, instead of concatenating the string, it overwrites it with the passed value on creation. If it matters (I don't think it does) the string contains numbers. Par example:
function myObj(strToConcat){
this.combinedString = "Hello " + strToConcat, /* have used + and .concat() without success */
}
var newObj = new myObj("1.2.3");
console.log(newObj.combinedString); /* says "1.2.3", the leading "Hello " is absent */
Can't seem to get this to concatenate the strings.
EDIT: I apologize, the error was outside the code that I thought responsible. Disregard please. My apologies.
You have error in your reference
console.log(myObj.combinedString);
should be
console.log(newObj.combinedString);
Running your code gives me SyntaxError: Unexpected token }. Replace the , at the end of the second line with a ; and I get the expected result of "Hello 1.2.3".

Weird JSON parsing behavior in js, "Unexpected token :"

As demonstrated in this jsfiddle, if you have a JS file and you create a JSON object without using it, it behaves differently depending on whether the keys(members) are wrapped in quotes or not.
valid code:{ a: 1};
invalid code: { "a": 1 };
What you will get is an error message (in Chrome, different for FF/IE, but still fails on syntax)
Uncaught SyntaxError: Unexpected token :
but if you use the object in some way, for example: alert({ "a": 1 }); everything is OK again.
Why does this happen?
The statement:
{ a: 1 };
is not an object literal. It's a block statement with one labeled expression in it. It's valid.
This:
{ "a": 1 };
is a syntax error because it's just not parseable. The quoted "a" starts an expression statement inside the block, but then the next token after the string is a colon, and there's no expression form that looks like an expression followed by a colon.
Now:
var x = { "a": 1 };
works because the "{" is not interpreted as the start of a block statement. That statement starts with var, so it's a variable declaration. Within the expression on the right side of the "=" token, the only thing that a "{" can mean is the start of an object literal. Similarly, note that:
({ "a": 1 });
is OK because the opening parenthesis makes the parser expect a nested subexpression, so again the "{" unambiguously means that it's the start of an object literal.
I just realized than when loading the JSON via require and the filename does not end on .json i get this error. Renaming the file to bla.json and it works fine.
This error can popup when doing a jQuery AJAX call using jsonp when jsonp is not necessary. Try switching your data type on your AJAX call if this is the case to normal json
$.ajax({
dataType: 'json', // try using json rather than json p
...
});

Categories