最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - " is JSON string - Stack Overflow

programmeradmin1浏览0评论

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

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

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

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

Why does the JavaScript segment encode the double quotes?

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

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

Error message: "SCRIPT1015: Unterminated string constant"

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

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

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

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

Why does the JavaScript segment encode the double quotes?

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

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

Error message: "SCRIPT1015: Unterminated string constant"

Share Improve this question edited Dec 3, 2014 at 10:46 Ranjith Venkatesh asked Dec 3, 2014 at 10:22 Ranjith VenkateshRanjith Venkatesh 1,3623 gold badges22 silver badges59 bronze badges 3
  • var json = JSON.parse('@Model.JsonData') – Ehsan Sajjad Commented Dec 3, 2014 at 10:24
  • The above ment does not work because the @Model.JsonTreeData encodes automatically and throws "SCRIPT1015: Unterminated string constant" – Ranjith Venkatesh Commented Dec 3, 2014 at 10:47
  • possible duplicate of How to remove &quot; from my Json in javascript? – Chaitanya Gadkari Commented Apr 23, 2015 at 10:19
Add a ment  | 

2 Answers 2

Reset to default 4

Replace &quot; with "

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);

In your controller Pass Model.JsonData this way

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

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

发布评论

评论列表(0)

  1. 暂无评论