如何正确解码使用Html.Raw(JSON.Encode(Model))编码的JSON字符串

How to properly decode a JSON string encoded using Html.Raw(Json.Encode(Model))?

本文关键字:JSON 何正确 Model 编码 字符串 Encode 解码 Html Raw      更新时间:2023-09-26

我正在将一些模型数据编码到一个html元素中,如下所示:

@Html.Raw(Json.Encode(Model));

返回的json字符串如下所示:

{"TestList":[{"FrequencyType":"1X","GCDs":"585.6","Identifier":"6144","SeqNo":9306,"SeqNoSpecified":true,"TSeqNo":8314,"TSeqNoSpecified":true,"TestDescr":"HBsAg"},{"FrequencyType":"1X","GCDs":"585.6","Identifier":"6124","SeqNo":9295,"SeqNoSpecified":true,"TSeqNo":8315,"TSeqNoSpecified":true,"TestDescr":"HCV Ab"},{"FrequencyType":"1X","GCDs":"585.3","Identifier":"6","SeqNo":9729,"SeqNoSpecified":true,"TSeqNo":8309,"TSeqNoSpecified":true,"TestDescr":"HD Monthly LS"}],"Frequency":[{"Key":"ANNUAL","Value":"Annually"},{"Key":"BIMONTH","Value":"Bi-Monthly"},{"Key":"BIWEEK","Value":"Bi-Weekly"},{"Key":"MON","Value":"Monthly"},{"Key":"1X","Value":"One Time"},{"Key":"QTR","Value":"Quarterly"},{"Key":"SMAN","Value":"Semi-Annual"},{"Key":"WEEK","Value":"Weekly"}]};

当我尝试使用JSON.parse解析时,我得到了一个错误:

arrayTestList = [];
var jsonTestList = $('#TestList').text();
jsonTestList = JSON.stringify(jsonTestList);
arrayTestList = JSON.parse(jsonTestList);
alert(arrayTestList.TestList[0]); // <===== this line is failing
Unable to get value of the property '0': object is null or undefined

如何将这个jsonTestList字符串转换为javascript数组,以便正确访问arrayTestList的元素?

编辑:

对不起,我忘了提我的编辑。基本上,上面的javascript代码位于Partial View 2中。我对模型进行json编码的代码在另一个Partial View 1中。从PV2,我无法访问PV1的模型对象,所以我只是将内容转储到div标记中,这样我就可以访问这个列表TestList元素。

尝试删除此行:

jsonTestList = JSON.stringify(jsonTestList);

jsonTestList已经是一个JSON字符串

问题现已解决。

我得到了一个无效字符,但无法立即识别是哪个字符导致了问题。我发现我的JSON字符串无效,因为Json.Encode方法输出了尾随分号。我验证了JSON字符串@http://jsonlint.com.

删除分号后,json字符串将作为JavaScript数组填充到arrayTestList对象中。

现在,正如上面两个答案中所提到的,只要这样就可以了,不需要JSON.stringify

var arrayTestList = [];
var jsonTestList = $('#TestList').text().replace(";","");
arrayTestList = JSON.parse(jsonTestList);
alert(arrayTestList.TestList[0]); 

为什么要使用Json.Encode?另外,在您的代码中,为什么要首先编写冗余代码?您使用的是JSON.stringifyJSON.parse同一对象。

jsonTestList = JSON.stringify(jsonTestList);
arrayTestList = JSON.parse(jsonTestList);

根据我的理解,只有Html.Raw可以工作

在JavaScript 中

var jsonObject = @Html.Raw(Model.TestList); //Here you will get JavaScript Object
var jsonTestList =  jsonObject.TestList;