在jQuery中将JSON字符串转换为对象

时间:2012-11-28 13:20:51

标签: jquery json

我有一个jQuery http请求,它以JSON字符串的形式返回一个对象。这里我要做的是将JSON转换为jQuery对象并将值分配给html元素......以下是要转换的对象的结构:

var Userrights = {

            Id: // an id element
            ScreenRights: // this is a list with following elements
            {
                ScreenName: 
                Create:
                Read: 
                Update: 
                Delete:
                Approve: 
                Access: 
                Print: 
                Email: 
            };
        };

现在,当我收到如下的JSON字符串时:

{
    "Id": "Manager",
    "ScreenRights": [{
        "ScreenName": "CustomerScreen",
        "Create": true,
        "Read": false,
        "Update": true,
        "Delete": false,
        "Approve": true,
        "Access": true,
        "Print": true,
        "Email": true
    },
    {
        "ScreenName": "TraderScreen",
        "Create": true,
        "Read": false,
        "Update": true,
        "Delete": false,
        "Approve": true,
        "Access": true,
        "Print": true,
        "Email": true
    },
    {
        "ScreenName": "DistributorScreen",
        "Create": true,
        "Read": false,
        "Update": true,
        "Delete": false,
        "Approve": true,
        "Access": true,
        "Print": true,
        "Email": true
    }]
}​

现在我将如何将此String转换为上述对象Structure?

2 个答案:

答案 0 :(得分:0)

Jquery的:

var obj = $.parseJSON(string);
console.log(obj);

话虽如此,如果你使用的是jQuery的.ajax,你可以设置dataType:'json'

答案 1 :(得分:0)

我认为您可以将json放入某个数组中,然后可以使循环按名称访问对象。

result[i].Create;
result[i].Read;