在客户端通过javascript或Jquery解析Json数据

时间:2012-11-24 11:10:24

标签: javascript jquery json

我想在客户端解析数据,我在序列化后将数据保存在输入字段中。

JavaScriptSerializer objJavaScriptSerializer = new JavaScriptSerializer();
string jsonString = objJavaScriptSerializer.Serialize(_statusVal);
jsonFmtStatusValue.Value = jsonString;

在客户端当我看到存储在输入字段中的数据字符串时,它就像这样

[
    {
        "nodeContentId": "1234_5678",
        "statusTypeId": "5678",
        "statusName": "Submitted by Customer",
        "dateTime": "/Date(1352745000000)/",
        "forceEmail": "on",
        "user": {
            "userId": "0",
            "userName": "admin"
        },
        "note": {
            "typeName": null,
            "dataValue": null
        }
    },
    {
        "nodeContentId": "1234_5678",
        "statusTypeId": "5678",
        "statusName": "Checked, Printed, Folded & Re-checked",
        "dateTime": "/Date(1353402060000)/",
        "forceEmail": "on",
        "user": {
            "userId": "0",
            "userName": "admin"
        },
        "note": {
            "typeName": null,
            "dataValue": null
        }
    }
]

我尝试解析Json数据的代码是:

    var JsonData = $("#<%=jsonFmtStatusValue.ClientID %>").val();
    obj = jQuery.parseJSON(JsonData)
    alert(obj.nodeContentId);

我在警报框中收到的信息: 的取消定义

无法弄清楚我应该使用什么进行解析。

1 个答案:

答案 0 :(得分:4)

(注意:我假设jsonFmtStatusValue最终成为页面上的inputtextarea。)

alert(obj.nodeContentId);中,obj数组,而不是数组中的对象。您最外层的JSON实体是一个数组,然后包含对象。

你可以这样看到第一个 nodeContentId

alert(obj[0].nodeContentId);

...当然其他的都在后续索引中,例如:

var obj = jQuery.parseJSON(JsonData);
var n;
for (n = 0; n < obj.length; ++n) {
    alert("obj[" + n + "].nodeContentId = " + obj[n].nodeContentId);
}