devgal
devgal

Reputation: 149

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))');

Upvotes: 4

Views: 5126

Answers (2)

Joe
Joe

Reputation: 2540

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"}]');

Upvotes: 6

Shaun Parsons
Shaun Parsons

Reputation: 362

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"}]');

Upvotes: 1

Related Questions