Escaping quotes in Newtonsoft JSON
Asked Answered
J

2

12

I've an object:

public class Test 
{
    public string Prop1 { get; set; }
}

I'd like to serialize it to json in a view, so in my cshtml:

<script type="text/javascript">
   var myJson = JSON.parse('@Html.Raw(JsonConvert.Serialize(Model.MyTest))');
</script>

It works, until Prop1 contains quotes, because it gets rendered as:

var myJson = JSON.parse('{"Prop1":"\"Quoted text\""}');

Unfortunately, such a line throws parse error. I know that it should be:

 var myJson = JSON.parse('{"Prop1":"\\"Quoted text\\""}');

How can I configure Newtonsoft to serialize it in a proper way?

Johanna answered 15/6, 2015 at 12:43 Comment(0)
S
11

You should not parse the string for a second time, since already serialized it as JSON, you can directly use it in Javascript (the JS in JSON).

var myJson = @Html.Raw(JsonConvert.Serialize(Model.MyTest));

Will output:

var myJson = {"Prop1":"\"Quoted text\""};

And, because you always need a JSFiddle to prove it works.

Suited answered 15/6, 2015 at 13:0 Comment(2)
Nice, works! The only drawback is that intellisense gets confused and marks line as invalid.Johanna
True. That is a known bug.Suited
S
0

This worked for me to get C# object into Javascript:

var objJSON = '@Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(MyObject).Replace(@"\""",@"\\""").Replace("'","\\'"))';
var obj = JSON.parse(objJSON);
Som answered 3/11, 2023 at 10:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.