Escape special JSON characters on Razor page so that JSON.parse can be used with a date reviver

Viewed 493

I’m using Asp.Net Core 3.1 MVC and am trying to serialize a model on a Razor page, but I need it to be encoded so that it will work with JSON.parse so that I can use a date reviver to convert date strings to date objects. Json.Serialize writes out the json in a way that it can be used without JSON.parse, so if you wrap it in single quotes to make it a string, special characters are not properly escaped and JSON.parse throws errors when characters such as "\" are encountered.

// Model definition { "myField": "abc\\def" }
<script type="text/javascript">
   var data = '@Json.Serialize(Model)',
       json = JSON.parse(data, myDateReviver);
</script>

I found a workaround, that I'd like to avoid using if at all possible.

// Model definition { "myField": "abc\\def" }
<script type="text/javascript">
   var data = JSON.stringify(@Json.Serialize(Model)),
       json = JSON.parse(data, myDateReviver);
</script>

Is there a proper way to string encode the result of @Json.Serialize so that it's compatible with JSON.parse?

0 Answers
Related