如何在JavaScript中获取具有多个级别的JSON字符串的子元素

时间:2012-12-08 02:30:28

标签: c# javascript json json.net

这是我的C#JSON解析器生成的JSON字符串:

{
    "NewDataSet": {
        "Table": [
            {
                "ResultId": "1",
                "AttachmentId": "1",
                "AttachmentName": "Report1",
                "RowsCount": "34",
                "NotifyUserName": "william",
                "InsBy": "developer",
                "InsAt": "2012-12-07T17:28:01.46+08:00",
                "IsNotify": "false"
            },
            {
                "ResultId": "2",
                "AttachmentId": "2",
                "AttachmentName": "Report2",
                "RowsCount": "37",
                "NotifyUserName": "william",
                "InsBy": "developer",
                "InsAt": "2012-12-07T17:28:15.57+08:00",
                "IsNotify": "false"
            },
            {
                "ResultId": "3",
                "AttachmentId": "3",
                "AttachmentName": "Report3",
                "RowsCount": "69",
                "NotifyUserName": "william",
                "InsBy": "developer",
                "InsAt": "2012-12-07T17:28:25.58+08:00",
                "IsNotify": "false"
            }
        ]
    }
}

然后我想将字符串解析为前端JavaScript来迭代值。 我这样做了。

  var jsonText;
        $.ajax({
            type: "POST",
            url: "Default.aspx/MethodWithNoParameterJSON",
            data: {},
            contentType: "application/json;charset=utf-8",
            dataType: "json",
            async: true,
            cache: false,
            success: function (msg) {
                //rulesName = dbtitle+msg.d;
                //rulesCount = +msg.d;
                jsonText = msg.d;
               alert(jsonText.NewDataSet.Table[0].ResultId), 
            },
            error: function (x, e) {
                alert("The call to the server side failed. " + x.responseText);
            }
        });

如何获取jsonText.NewDataSet.Table[0].ResultId等子元素数据?每当我调用alert(jsonText.NewDataSet.Table[0].ResultId)时,它总会提示null或未定义的对象。

2 个答案:

答案 0 :(得分:1)

为什么使用msg.d设置jsonText变量? .d属性来自哪里? msg参数应该已经是从JSON响应创建的对象。试试这个:

msg.NewDataSet.Table[0].ResultId

(请注意,您的jsonText变量命名错误:此时您所拥有的不是JSON或“text”,它是一个对象 - 或者,在您的情况下,undefined因为{ {1}}未定义。但您尝试将其用作对象,而不是JSON。)

答案 1 :(得分:0)

错字?我认为应该是

jsonText.NewDataSet.Table[0].ResultId // replace RulesId with ResultId