4

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))');
1
  • Keep in mind, apostrophe in C# are char, not strings. Commented Nov 18, 2016 at 8:17

2 Answers 2

6

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"}]');
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Joe for quick reply and help....you have also removed Hyphen(-) from the string between "Me Be". Should I need to remove that also?
C# gives the non-literal interpretation to "\n" here, not JavaScript. You can tell because there's no JavaScript here and yet you still have the problem.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.