1

这可能很容易,但我需要访问这个 JSON 对象中的值。我不知道怎么做。这是对象:

{
    "COLUMNS": ["NAME"],
    "DATA":  [["YOUNG, MARIA              "]]
}

我希望“obj.NAME”会这样做,但它说它是未定义的。这是我的 AJAX 调用:

$.ajax({
                        //this is the php file that processes the data and send mail
                        url: 'components/Person.cfc',

                        //GET method is used
                        type: "POST",

                        //pass the data        
                        data: {
                            method: "getGroup",
                            uid: $('#cardText').val()
                            },

                        success: function(response) {

                            var obj = $.trim(response);
                            var obj = jQuery.parseJSON(obj);
                            $('#form_result').html(obj.NAME);

                        },
4

2 回答 2

2

在您的代码中,以下示例显示了如何访问此特定 JSON 对象中的属性:

alert( obj.COLUMNS[0] );  // alerts the string "NAME".

alert( obj.DATA[0][0] );   // alerts "YOUNG, MARIA              "

要理解为什么这是输出,理解和学习阅读构成 JSON 的符号很重要:

{} = object

[] = array

你的 JSON:

{
    "COLUMNS": ["NAME"],
    "DATA":  [["YOUNG, MARIA              "]]
}

由于最外面的部分用花括号表示,我们知道 JSON 表示的是一个对象,而不是一个数组。该对象有两个属性,它们都是数组,因为分配给它们的值被括在括号中。

第二个属性 DATA 实际上是一个大小为 1 的数组,其中包含另一个大小为 1 的数组,其中包含一个字符串。

最后,在您的代码中,您尝试访问 NAME,它是一个值,而不是一个属性。JSON 最后一点要了解 JSON 是所有对象都由键/值对表示。您使用密钥来访问值。obj.COLUMNS 检索第一个数组,而 obj.DATA 检索第二个数组。

NAME 不是属性。相反,它是分配给数组的值。

为了帮助您了解如何访问 JSON,请练习访问不同对象的属性。此外,您可以将现有对象转换回 JSON 并在控制台中显示它们,以便查看它们在 JSON 中的结构:

var your_object = new Object();
your_object.name = "Bob";
your_object.skills = ["programmer","debugger","writer"];

console.info( JSON.stringify( your_object ) );

// this would convert the object to JSON. Going the other direction could help 
  // you further understand the concepts under the hood. Here is the output:
{ "name" : "Bob", "skills" : [ "programmer" , "debugger" , "writer" ] }
于 2012-05-19T02:31:03.677 回答
0

通过 parseJSON 运行对象后,您将拥有一个有两个孩子的对象

myObj = parseJSON (yourJSONStringAbove);
myObj.COLUMNS ; // this is an array containing one item whose value is "name"
myObj.DATA; // this is an array of arrays, it contains one array which has one value

so, myObj.data[0][0] ; // this is "YOUNG, MARIA          "
于 2012-05-19T02:32:24.143 回答