JSON中的特殊字符打破了JS

时间:2021-07-13 15:30:20

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

在ASP MVC控制器中,我创建了一个ViewBag变量,其中包含要在我的页面上加载的项目列表:

    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.

在我的Knockout加载函数中,我解析列表并删除打破JSON.parse()函数的换行符。

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?

但是,其他特殊字符偶尔会破坏JSON.parse()函数。有没有办法在JS端的控制器上过滤掉这些?

1 个解决方案

#1


0  

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.

您可以将其作为对服务器的JavaScript请求的响应传递给您,而不是将您的JSON直接写入页面的HTML。

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.

但是,如果您想直接在您的cshtml中编写它,请看一下这篇文章:如何使用Razor将未编码的Json写入我的View?它显示了如何将未编码的JSON打印到具有一些特殊功能的页面编码的字符不会导致进一步解析的问题。

#1


0  

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.

您可以将其作为对服务器的JavaScript请求的响应传递给您,而不是将您的JSON直接写入页面的HTML。

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.

但是,如果您想直接在您的cshtml中编写它,请看一下这篇文章:如何使用Razor将未编码的Json写入我的View?它显示了如何将未编码的JSON打印到具有一些特殊功能的页面编码的字符不会导致进一步解析的问题。