无法解析返回的Jquery / .NET Core JSON

时间:2019-03-15 16:22:37

标签: javascript jquery json asp.net-core

这是我发送给控制器的内容:

  

“ [{{\” PropertyName \“:\” fewfewf \“,\” Key \“:\” ewgwewe \“,\” PrimaryValue \“:\” \“,\” SecondaryValue \“:\” \ “,\” TertiaryValue \“:\” \“,\” MinimumValue \“:\” \“,\” MaximumValue \“:\” \“},{\” PropertyName \“:\” rwhjyjut \“,\ “ Key \”:\“ jtyjyt \”,\“ PrimaryValue \”:\“ \”,\“ SecondaryValue \”:\“ \”,\“ TertiaryValue \”:\“ \”,\“ MinimumValue \”: \“ \”,\“ MaximumValue \”:\“ \”}]“

这是我在解析并再次对其进行序列化后从服务器收到的信息。

enter image description here 我很困惑,因为我什么都没改变。当我尝试将其解析为Jquery时,出现此错误:

  

未捕获到的SyntaxError:意外的令牌和JSON中的位置2

这是jquery代码

if ("@Model.FormPropertiesList".length !== 0) {
    console.log($.parseJSON("@Model.FormPropertiesList"));
}

我想念什么吗?

编辑:这是我的服务器端代码

var list = JsonConvert.DeserializeObject<List<NewFormPropertyViewModel>>(Input.FormPropertiesList);
Input.FormPropertiesList = JsonConvert.SerializeObject(list);
return View("Create", Input);

这是我将字符串转换为JSON的方式

$("#@Html.IdFor(m => m.FormPropertiesList)").val(JSON.stringify(dataSet));

3 个答案:

答案 0 :(得分:0)

首先替换您的“&”

var serverrep= "[{&quot;PropertyName&quot;:&quot;fewfewf&quot;,&quot;Key&quot;:&quot;ewgwewe&quot;,&quot;PrimaryValue&quot;:&quot;&quot;,&quot;SecondaryValue&quot;:&quot;&quot;,&quot;TertiaryValue&quot;:&quot;&quot;,&quot;MinimumValue&quot;:&quot;&quot;,&quot;MaximumValue&quot;:&quot;&quot;}]"


var serverRepWithoutQuots=serverrep.replace(/&quot;/g, '"');
console.log(serverRepWithoutQuots)
console.log(JSON.parse(serverRepWithoutQuots))

答案 1 :(得分:0)

在将JSON传递到模板然后传递给Django中的js文件时,出现了这样的问题。当您在Django中执行此操作时,您将从上下文视图中传递某些内容,然后在Django模板中执行类似的操作

var someName = {{ fromView }};

我把它用双引号引起来

var someName = "{{ fromView }}";

因此它在转义的JSON中转义了双引号。我花了大约2个小时的时间来弄清楚到底是什么原因,而我实际上不得不将双引号更改为单引号,因为它是将其读取为带双引号的字符串,而在字符串中又带有另一个带双引号的字符串(json字符串)< / p>

var someName = '{{ fromView }}';

要点是,我将检查JSON以确保您没有以错误的方式传递它,并且编码不正确/在某处添加了额外的引号

答案 2 :(得分:0)

字符串是HTML编码的。您可以使用@HTML.Raw告诉剃刀将string照原样放置。字符串被编码的原因之一是出于安全目的。假设您正在尝试显示刚从数据库中获取的某些数据,并且该数据具有一些“恶意” JavaScript,尽管此代码对数据库无害,但是一旦呈现视图,它将影响客户端。您可以尝试:

if ("@Model.FormPropertiesList".length !== 0) {
    console.log(JSON.parse("@HTML.Raw(Model.FormPropertiesList)"));
}