在JavaScript中使用反斜杠读取Json String时出错

时间:2012-01-23 06:51:30

标签: javascript json escaping backslash

我已经在Json对象中转换了一个C#类,然后我将该字符串化为json对象,然后使用反斜杠转换(转义字符),当我使用下面的代码读取json字符串时,它在alert中给出了未定义的消息。

<script>



    var jsString = { "JsonString": ["{\"reachoutid\":1,\"user_ID\":1,\"question\":\"Best CMS in Microsoft  .Net\",\"anonymous\":false,\"shared\":false,\"create_date\":\"\\/Date(-62135596800000)\\/\",\"update_date\":\"\\/Date(1327300086183)\\/\",\"status\":0,\"start_date\":\"\\/Date(-62135596800000)\\/\",\"end_Date\":\"\\/Date(-62135596800000)\\/\",\"reachoutfactorsList\":null,\"reachoutchoicesList\":[{\"reachoutid\":0,\"choice_ID\":4,\"orders\":0,\"description\":\"Sitecore\",\"preachOutID\":0,\"pchoice_ID\":4,\"porders\":0,\"pdescription\":\"Sitecore\"},{\"reachoutid\":0,\"choice_ID\":5,\"orders\":0,\"description\":\".Net Nuke \",\"preachOutID\":0,\"pchoice_ID\":5,\"porders\":0,\"pdescription\":\".Net Nuke \"},{\"reachoutid\":0,\"choice_ID\":6,\"orders\":0,\"description\":\"Drupal\",\"preachOutID\":0,\"pchoice_ID\":6,\"porders\":0,\"pdescription\":\"Drupal\"}],\"detail\":\"Write more text to check progress bar work properly.\",\"set_Listof_Tags\":null,\"tag\":null,\"get_Listof_Tags\":null,\"userstatus\":null,\"actType\":\"RO\"}"], "_getList_MyActivities": null, "_getList_MyPeersActivities": null, "userID": 1 }

    for (i = 0; jsString.JsonString.length > i; i++) 
    {

        alert(jsString.JsonString[i].reachoutid);

        //"Giving Undefined Message "

    }

</script>

2 个答案:

答案 0 :(得分:2)

您的JSON存储为字符串,而不是本机对象。要将其转换回来,请将alert( ... )行改为使用JSON.parse( ... ),如下所示:

    alert( JSON.parse(jsString.JsonString[i]).reachoutid )

答案 1 :(得分:0)

不应引用您的JSON。如果是,JS解释为字符串而不是对象

var jsObject = { "JsonString": [{"reachoutid":1,"user_ID":1,"question":"Best CMS in Microsoft  .Net","anonymous":false,"shared":false}]} // etc.