简体   繁体   中英

Special characters in JSON are breaking JS

In the ASP MVC controller, I created a ViewBag variable with the list of items to be loaded on my page:

    public ActionResult Items()
    {
        ViewBag.itemList = Repo.GetItems(); // Returns list of Items
        return View("Items");
    }

On the page side, I am parsing this data:

@{
Newtonsoft.Json.JsonSerializerSettings jsonSettings = new Newtonsoft.Json.JsonSerializerSettings { ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() };
var jsonData = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model, Newtonsoft.Json.Formatting.Indented, jsonSettings));
var serial = new System.Web.Script.Serialization.JavaScriptSerializer();
var items = serial.Serialize(ViewBag.itemList);
}

In my Knockout load function, I parse the list and remove newline characters which break the JSON.parse() function.

self.load = function () {
var itemsEscaped = '@Html.Raw(items.Replace("'", "\\'"))'.replace("\n", "\\n");
var someItems = JSON.parse(itemsEscaped);
ko.mapping.fromJS(someItems, self.itemMapping, self.someItems);
}

However, other special characters occasionally break the JSON.parse() function. Is there a way to filter these out either on the controller on JS side?

Instead of writing Your JSON directly to the page's HTML, You could pass it as a response to a JavaScript request to the server.

If, however, You would like to write it directly in Your cshtml, take a look at this post: How do I write unencoded Json to my View using Razor? , which shows how to print unencoded JSON to the page with some of the special characters encoded not to cause issues with further parsing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM