user380689
user380689

Reputation: 1794

Escape special characters in JSON encoded string

I'm using Knockout with MVC and the standard method i've seen to get a view model for knockout is like this:

var model = '@Html.Raw(Json.Encode(Model))';
var viewModel = ko.mapping.fromJSON(model);

But if my model has string properties with special characters in them, e.g. '\r\n' I get a JSON parse error 'unexpected token'.

So I believe I need to escape these characters so they are like '\\r\\n'. How to do this?

I know I can just do this for this particular case:

var model = '@Html.Raw(Json.Encode(Model).Replace(@"\", @"\\"))';

but there may be others... tabs, single quotes.

Below is an example of the actual rendered model in the browser:

var model = '{"Id":4465,"TextContents":["EYE FILLET STEAK\r\nLINE 2 IS HERE"]}';

Upvotes: 3

Views: 7335

Answers (1)

Ilia G
Ilia G

Reputation: 10211

Your model is a string, not a JSON. It evaluates escape characters before JSON parsed (if at all?) Why do you need the quotes? Just remove them.

var model = @Html.Raw(Json.Encode(Model));

Upvotes: 8

Related Questions