Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.parse string invalid character issue

I am not able to figure out what is the problem with JSON in the following code.

This is working fine:

var a = JSON.parse('[{"label":"not applicable"},{"label":"see items"},{"label":"40 days"},{"label":"suntest"}]');

But this throws an exception, "Invalid Character" :

var b = JSON.parse('[{"label":"234"},{"label":"Sunny AG, Sunny Me- Be Cars, Ben., Bu 60, DE 71059, Sind, Discharge p no. 9711\r\n"},{"label":"C207346"}]');

While debugging I copied above runtime code. Actual code is in C# MVC as:

var a= JSON.parse('@Html.Raw(Json.Encode(Model.ShipToAddressCodeList))');
like image 770
devgal Avatar asked Mar 10 '23 15:03

devgal


2 Answers

You need to escape the \r\n. JavaScript interprets the \'s in \r\n as escape characters, but really they are part of the string and should stay. Adding another \ in front of each \ fixes it, by escaping the escape character so the JSON parser treats it literally:

var b = JSON.parse('[{"label":"234"},{"label":"Sunny AG, Sunny Me- Be Cars, Ben., Bu 60, DE 71059, Sind, Discharge p no. 9711\\r\\n"},{"label":"C207346"}]');
like image 165
Joe Avatar answered Mar 19 '23 12:03

Joe


You need to escape your \r\n as \\r\\n

var b = JSON.parse('[{"label":"234"},{"label":"Sunny AG, Sunny Me- Be Cars, Ben., Bu 60, DE 71059, Sind, Discharge p no. 9711\\r\\n"},{"label":"C207346"}]');
like image 29
Shaun Parsons Avatar answered Mar 19 '23 14:03

Shaun Parsons