Javascript JSON.parse Invalid Character Error - javascript

I have a JSON data as below which getting from remote URL.
{"myitems":[{\"NAME\":\"JOHN\"},{\"NAME\":\"MICHAEL\"},{\"NAME\":\"CATTY\"},{\"NAME\":\"DAVID\"}]}
in JavaScript I want to parse
JSON.parse(mydata);
But I'm getting the error as:
Invalid Character
What can I do?

You need to fix the errors in the JSON. This fix should be done at source (i.e. you should change the report URL that is outputting invalid JSON so it outputs valid JSON instead).
Your string literals need to start and end with " (not \"). With the exception of "myitems", all of them have that error.

You have to remove slashes this will fix your issue:
Ex:
var str='{"myitems":[{\"NAME\":\"JOHN\"},{\"NAME\":\"MICHAEL\"},{\"NAME\":\"CATTY\"},{\"NAME\":\"DAVID\"}]}';
var output=JSON.parse(str.replace(/\\/g, ""));
above example will gives you output.

Related

Why does json.parse break? and how to fix it

I have the following data coming in from my server into my js code, from my server.
{"triggers": [{"message_type": "sms","recipients": "[\"+91xxxxxxxxx\",\"+91xxxxxxxxx\"]","message": "This is a test"}]}
My code parses the above json string in the following manner.
data = '{"triggers": [{"message_type": "sms","recipients": "[\"+91xxxxxxxx\",\"+91xxxxxxxx\"]","message": "This is a test"}]}'
parsed = JSON.parse(data);
This throws the following exception
Uncaught SyntaxError: Unexpected token + in JSON at position 54
at JSON.parse (<anonymous>)
at eval (eval at <anonymous> (entry.html:2), <anonymous>:1:6)
at entry.html:298
I did a little bit of further digging and found the source of the json string.
Here is where the string is coming in from my python code
data = {"recipients": "[\"+91xxxxxxxxx\",\"+91xxxxxxxx\"]"} # This data comes in from my database, and I can't do anything about what quotes are used.
javascript_supplied_data = json.dumps(data) #This data goes to the frontend via webhook
I tried putting the same data into a json view via this online viewer, and it didn't throw any error and displayed the data correctly.
What I can't understand is, I am doing a json.dumps in my python code, so the string response should be json parsable. So why does JSON.parse throw this error?
Is there something wrong with the json libraries at the python end or the javascript end, or am I too much of a noob?.
Please help me figure out what is causing this issue, and how to solve it.
NOTE: I don't have any control over the string that comes in from the server.
When you have valid JSON, but put it in a string literal, the escapes treated by the literal notation in JavaScript make the string different. The backslashes are interpreted as for escaping the next character.
So either you have to go through the string literal and double all the backslashes, or you can apply String.raw to the string literal as template string:
var data = String.raw`{"triggers": [{"message_type": "sms","recipients": "[\"+91xxxxxxxx\",\"+91xxxxxxxx\"]","message": "This is a test"}]}`;
var parsed = JSON.parse(data);
console.log(parsed);
Note however, that the JSON you posted at the start of your question is valid.
On the other hand, the error you get indicates that the \" just before the first + is interpreted as just ". This means the \ is not actually there when the string is received from the server. This is usually caused by a similar escaping problem at the server side, where the programmer intended to send the backslash to the client, but actually just escaped the " on the server, which resulted in only the " being sent to the client and not \".
You have to use single quotes here while escape sequence.
if we use double quotes for escape sequence here it will result in
"recipients": "["+91xxxxxxxx","+91xxxxxxxx"]"
double quotes inside double quotes which is why your code breaks.
data = '{"triggers": [{"message_type": "sms","recipients": "[\'+91xxxxxxxx\',\'+91xxxxxxxx\']","message": "This is a test"}]}';
parsed = JSON.parse(data);
console.log(parsed)

Why JSON.parse fail while eval() work like a charm?

For some reason this formated JSON always fail for me when I try to use JSON.parse().
let string = '[{"appearances":{"0":[138545,""],"1":[138547,""],"3":[138548,""]},"bonustrees":[240,241,264],"classs":2,"displayid":138545,"dps":18.67,"flags2":8192,"id":113965,"level":138,"name":"4Sorkas Chainfist","reqlevel":100,"slot":13,"slotbak":13,"source":[2],"sourcemore":[{"bd":1,"z":6967}],"specs":[269,581,260,263,577],"speed":2.60,"subclass":13,modes:{"mode":458752,"4":{"count":229,"outof":21731},"65536":{"count":28,"outof":4490},"131072":{"count":18,"outof":4719},"262144":{"count":183,"outof":3517}},count:229,stack:[1,1]}]';
console.log(eval(string)); // Output as expected from JSON.parse
console.log(JSON.parse(string)); // SyntaxError: Unexpected token m in JSON at position 341
JSON.parse fails because it can only process JSON syntax. Your string is not a valid JSON -- it says so in the error message you're receiving.
The error points to an m from the modes from this part:
"subclass":13,modes:{"mode":458752,
You've also got a couple of more quotes missing down the line; you might want to check that out.
eval executes JavaScript code passed in as a string -- as if you've written it in code in the place where you're running the function. Since your string is valid JavaScript, it works without a problem.

Extra Square brackets Get added when retrieve Json data

I am Trying to retrieve data from json in my code. Json data doesn't contain any brackets. It is just any array separated by commas(,). My Problem is that when I get data using $scope, an extra sqaure bracket get added outside my output. Demo of my code is
controller.js
$http.get("serverUrl")
.success(function(data) {
$scope.sour = data;
})
.error(function(err) {
console.log("Error in source: "+JSON.stringify(err));
});
html
<div>
{{sour}}
</div
expected json
data
error
[data]
I have tried old stack solutions but none of them worked out for me.
Please share if anyone know why this error being produced, As I have used this method a hundred times before but never faced this problem.Regards.
After trying found out a solution.
.toString().replace();
solved out my problem.
As per how JSON.stringify should work as specified here, the result that you explained is as expected.
Let separator be the result of concatenating the comma character,
the line feed character, and indent.
Let properties be a String
formed by concatenating all the element Strings of partial with each
adjacent pair of Strings separated with separator. The separator
String is not inserted either before the first String or after the
last String.
Let final be the result of concatenating "[", the line
feed character, indent, properties, the line feed character,
stepback, and "]"
Which will result in a valid JSON String. The format you are requesting is confusing and is probably an invalid JSON. You can try checking the JSON using some JSON validator online. (Notice that [1,2,3,4] is valid where as 1,2,3,4 is invalid)
You are probably having a service that is expecting a malformed JSON, it will be better to fix that part instead of duck taping your JSON.
Meanwhile, the only thing you are explaining is the format you are getting and the format that is working. You haven't still specified where exactly the error happens? Is it error from HTTP request? Is it error thrown in Javascript? What is causing the error? What error messages are you getting?

Unexpected error while parsing JSON in javascript

I am getting a string object after splitting from a text. Now I am trying to convert that text to a JSON object.
Text after Splitting
{location:"Web",initial:"",firmType:"",toaxfrtype:""}
When I am trying to parse it using JSON.parse, I am getting an error,
SyntaxError: Unexpected token l.
I have some other string value as the same in the above text. It was parsing fine using JSON.parse. Only the above string is not working.
Can anybody help me in this issue.
You need quotes " so change
{location:"Web",initial:"",firmType:"",toaxfrtype:""}
to
{"location":"Web","initial":"","firmType":"","toaxfrtype":""}
I have attached the image where it says valid now after correction. You can online validators to validate it first.
This is not JSON. You need to quote all Strings, including the keys.

javascript eval json with base64 encoded field

I am using sun.misc.BASE64Encoder to encode an encrypted value, which is then added to a JSON field and subsequently sent to the client. I use Javascript's eval() function on the client to create an object from the JSON code. When eval() runs, it gives the error:
unterminated string literal
There are other fields in the JSON code, but I've narrowed the error specifically to the base64 encoded field. Here's the offending line of javascript code:
var result = eval( '(' + xhr.responseText + ')' );
Here's the JSON object from the Servlet:
{
'resource':'resource?Signature=j79r/2Hly+HqhS/6fdd+prfsR+kUNijUvDN0QJ14ZR43gzYScOMDypt/crks/CEphTUXVptJvSol
1ZOOvScCUhNOCb7dZk/3MKnI5tOewSACXK32/OJNd8hYpZtSTn+WhA6+f9BUIUZWA83U8Cud/Tb8V
R1yQWbDGG/mM/NiUSiY=',
'url':'http://somesite.com/pr'
}
I'm not sure why eval is dying, but it seems the value of the 'resource' JSON field contains something it doesn't care for.
Thanks in advance.
Tim
I think it may be because your JSON appears to have line breaks in it. If you remove them, does it work?

Categories