Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

262
Views
Escaping quotes in Newtonsoft JSON

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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!