2015-07-13 126 views
2

我試圖訪問我的JSON文件的某些字段的值。如何訪問多維JSON數據?

console.log(objects.assignments.header.report_type);

我想打印出來HOMEWORK


的Javascript

$.ajax({ 

     url: "/BIM/rest/report/assignment", 
     type: "POST", 
     dataType : "json", 
     data: { 
     assessmentId: "206a9246-ce83-412b-b8ad-6b3e28be44e3", 
     classroomId: "722bfadb-9774-4d59-9a47-89ac9a7a8f9a" 
     }, 

     success: function(objects) { 

     console.log(objects.assignments.header.report_type); 

     // Result : Uncaught TypeError: Cannot read property 'report_type' of undefined 

JSON數據 - 我從AJAX調用回

{ 
    "assignments": [ 
    { 
     "assignmentId": "SUMMARY", 
     "name": "Summary", 
     "header": { 
     "section_num": "9.4", 
     "report_type": "HOMEWORK", 
     "problem_set": "Summary", 
     "start_time": null, 
     "student_am": 0, 
     "student_total": 5, 
     "due_time": null, 
     "submit_am": 0, 
     "submit_total": 0, 
     "avg_score": "0.0", 
     "danger": 0, 
     "danger_list": "", 
     "warning": 0, 
     "warning_list": "", 
     "success": 0, 
     "success_list": "" 
     } 
    } 
    ] 
} 

如何正確訪問這些數據?

任何提示/幫助對我來說意義重大。

在此先感謝。

回答

3

assignments是一個數組,所以您需要訪問特定元素

console.log(objects.assignments[0].header.report_type); 
           ^^^ 
3

$阿賈克斯({

url: "/BIM/rest/report/assignment", 
    type: "POST", 
    dataType : "json", 
    data: { 
    assessmentId: "206a9246-ce83-412b-b8ad-6b3e28be44e3", 
    classroomId: "722bfadb-9774-4d59-9a47-89ac9a7a8f9a" 
    }, 

    success: function(objects) { 

    console.log(objects.assignments[0].header.report_type); 
+0

頭是一個對象。它應該是header.report_type – nikhil

+0

快速編輯。我沒有辦法。 ... – ihue

+0

是的...這是在趕時間:) – AkshayJ

3

由於assignments是一個數組爲此,必須指定訪問其內部性能的索引來訪問使用。

objects.assignments[0].header.report_type 
1

{}表示您有一個對象有鍵值對

[]表示它是一個有索引(如果你喜歡的位置)值對的數組。

var myObject = { 
    'a_key':'A_value', 
    'b_key':'B_value', 
    'c_key':'C_value' 
    }; 

var myArray = [ 
    'A_value', 
    'B_value', 
    'C_value' 
    ]; 

要訪問的對象的值使用在陣列中的關鍵

console.log(myObject.a) // A_value 
console.log(myObject['c']) // C_value 

值可用由索引(從零開始)

console.log(myArray[0]) // A_value 
console.log(myArray[2]) // C_value 

可以有一個數組的物體或包含某些陣列的物體

所以在您的示例中它將是:

console.log(objects.assignments[0].header.report_type) 
      ^  ^ ^^ ^
      variable key index key  key 
      name  1st lvl  1st lvl 2nd lvl 
0

假設你有多個值的數組中,並希望訪問所有這些:

for (var i = 0; i < objects.assignments.length; i++) { 
    console.log(objects.assignments[i].header.report_type); 
}