javascript "是 JSON 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27269135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 07:15:48  来源:igfitidea点击:

" is JSON string

javascriptasp.net-mvcjsonencodingjstree

提问by Ranjith Venkatesh

I have a JSON string which looks like this when displayed in an ASP.NET MVC page using @Model.JsonData

我有一个 JSON 字符串,当使用 @Model.JsonData 在 ASP.NET MVC 页面中显示时,它看起来像这样

[
  {
    "id": 123,
    "text": "Consumer",
    "parent": "#";
  }
]

When I use the same @Model.JsonData in the JavaScript code it is encoded as:

当我在 JavaScript 代码中使用相同的 @Model.JsonData 时,它被编码为:

[
  {
    "id": 123,
    "text": "Consumer",
    "parent": "#"
  }
]

Why does the JavaScript segment encode the double quotes?

为什么 JavaScript 段要对双引号进行编码?

When the double quotes are encoded the jstree plugin expecting JSON data does not work.

当双引号被编码时,需要 JSON 数据的 jstree 插件不起作用。

<script>
    $(function () {
        $('#jstree').jstree({
            'core': {
                'data': function ()
                {
                    var jsonTreeData = @Model.JsonTreeData;
                    return jsonTreeData;
                }
            }
        });
    });
</script>

Error message: "SCRIPT1015: Unterminated string constant"

错误消息:“SCRIPT1015:未终止的字符串常量”

回答by Amy

Replace &quot;with "

替换&quot;"

var data = JSON.parse("[{&quot;id&quot;: 123,&quot;text&quot;: &quot;Consumer&quot;,&quot;parent&quot;: &quot;#&quot;}]".replace(/&quot;/g,'"'));

console.log(data);

回答by Arash.Zandi

In your controllerPass Model.JsonDatathis way

在您的控制器中通过这种方式传递Model.JsonData

Model.JsonData = new HtmlString("Your String or Json");

Add using Microsoft.AspNetCore.Html;if HtmlString is not accessible.

使用 Microsoft.AspNetCore.Html添加如果 HtmlString 不可访问。