Reputation: 146
On trying to parse the following string on titanium Studio for mobile app project, I get the
error: Unexpected token at profileSkills":"Analysis
des='[{"jobId":0,"jobPositionName":"NA","companyId":0,"companyDisplayName":"NA","profileSkills":"Analysis\r\nAnalysis\r\nQuality Assurance\r\nProject Management\r\nProgrammer Analyst\r\n"}]';
desjson=JSON.parse(des);
Can anyone help me , whether I can parse strings containing escape charaters using JSON.
If not, could you tell me the procedure to it.
Upvotes: 1
Views: 2116
Reputation: 700720
You have two \r\
in the string, that should be \r\n
. Change those, and it validates as correct JSON.
Upvotes: 0
Reputation: 413976
You need to encode the special characters with double-backslashes, because the JSON parser will expect them to be escaped.
var des='[{"jobId":0,"jobPositionName":"NA","companyId":0,"companyDisplayName":"NA","profileSkills":"Analysis\\r\\nAnalysis\\r\\nQuality Assurance\\r\\nProject Management\\r\\nProgrammer Analyst\\r\\n"}]';
If you are actually declaring the JSON string as a JavaScript string literal, then you have to account for the fact that when the JavaScript parser sees those escaped characters, it'll build a string with the real carriage return and line feed characters. The JSON parser coming along after that won't like them.
If, on the other hand, your JSON is really coming from a server, then the JSON "on the wire" should not have doubled backslashes.
I should also note that there's rarely any reason to put a JSON string as a literal in JavaScript code. It might as well be a JavaScript object literal, in most cases. (I acknowledge that there might be some reason for it, of course.)
Upvotes: 1