【发布时间】:2022-01-21 13:15:53
【问题描述】:
我有一个Product 课程。我有一个例子。我想在我的 Razor 页面和浏览器 JavaScript 中都可以访问它。
我的想法是我可以将Product 渲染到页面中并使用JSON.parse 解析它。
Product.cshtml:
@{
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DictionaryKeyPolicy = JsonNamingPolicy.CamelCase
};
}
<script>
var productJson = '@Html.Raw(JsonSerializer.Serialize(product, options))`;
var product = JSON.parse(productJson); // here I encounter error
</script>
但我的产品有一个名为Description 的字段,在其中我有新的行。因此JSON.parse 方法抱怨:
VM27754:1 Uncaught SyntaxError: Unexpected token
在 JSON 中的位置 246
在 JSON.parse()
在:1:6
我能做什么?如何在我的序列化 JSON 中转义换行符?有没有更好的办法?
【问题讨论】:
-
请注意,如果您将未引用的 json 打印到 javascript 变量分配,则不需要使用 JSON.parse()。 JSON 缩写代表 Javascript Object Notation
-
错误信息表明您的 JSON 格式错误。
标签: javascript c# json razor