当我尝试在JavaScript中解析JSON时,为什么会出现错误

时间:2014-11-01 22:43:09

标签: javascript asp.net-mvc json asp.net-mvc-4 razor

我在ViewBag的帮助下将JSON传递给剃刀视图页。

以下是动作功能中的代码:

    public ActionResult GmailOAuthCallback(string code)
    {
        object contacts = GmailServiceWorkflow.GetContacts(code);
        string json = new JavaScriptSerializer().Serialize(contacts);
        ViewBag.name = json;
        return View("SomeWindow");
    }

在剃刀视图页面,我想将JSON解析为对象。

以下是razor页面中的代码:

function myFunction() {
        var arrObject = JSON.parse("@ViewBag.name");
        alert(arrObject[0].firstName);
        }  

但是我收到了这个错误:

SyntaxError:JSON.parse:JSON数据第1行第3列的预期属性名称或'}'

知道为什么我会收到此错误以及如何修复它?

1 个答案:

答案 0 :(得分:2)

您可以通过将集合传递给视图

来实现此目的,而不是使用JavaScriptSerializer
public ActionResult GmailOAuthCallback(string code)
{
  object contacts = GmailServiceWorkflow.GetContacts(code);   
  ViewBag.name = contacts ;
  return View("SomeWindow");
}

然后在脚本中

function myFunction() {
  var arrObject = JSON.parse('@Html.Raw(Json.Encode(ViewBag.name))');
  alert(arrObject[0].firstName);
}