2012-09-15 191 views
-1

我有一個頁面向REST風格的Web服務發送請求(通過php和curl)。該頁面接收一個JSON對象作爲響應。我正在嘗試使用返回的數據填充某些表單域。這被迴盪在我的網頁的對象中的JavaScript看起來像:訪問JSON對象數據

var obj = { 
    "NPI": [ 
{ 
    "NPI": "123456789", 
    "EntityType": "Individual", 
    "IsSoleProprietor": "N", 
    "LastName": "Smith", 
    "FirstName": "John", 
    "MiddleName": "D", 
    "NameSuffix": "JR.", 
    "Credential": "MD", 
    "FirstLineMailingAddress": "PO BOX 123", 
    "MailingAddressCityName": "SCOTTSDALE", 
    "MailingAddressStateName": "AZ", 
    "MailingAddressPostalCode": "85255-0162", 
    "MailingAddressCountryCode": "US", 
    "MailingAddressTelephoneNumber": "888-123-4567", 
    "MailingAddressFaxNumber": "888-123-4567", 
    "FirstLinePracticeLocationAddress": "123 DR", 
    "SecondLinePracticeLocationAddress": "#278", 
    "PracticeLocationAddressCityName": "SCOTTSDALE", 
    "PracticeLocationAddressStateName": "AZ", 
    "PracticeLocationAddressPostalCode": "85266-2273", 
    "PracticeLocationAddressCountryCode": "US", 
    "PracticeLocationAddressTelephoneNumber": "888-123-4567", 
    "PracticeLocationAddressFaxNumber": "888-123-4567", 
    "EnumerationDate": "09/20/2006", 
    "LastUpdateDate": "02/07/2011", 
    "GenderCode": "M", 
    "Gender": "Male", 

    } 
    ] 
}; 
alert(obj.NPI.NPI); 

什麼是訪問這些對象屬性的語法。下面的警報聲明不起作用(警告「未定義」)。

感謝您的幫助

回答

0

嘗試obj.NPI[0].NPI這應該工作

的propblem是第一NPI是一個數組不是一個對象,因爲[]的存在,所以你要哪個元素的選擇陣列

0

您的obj.NPI是一個對象數組。

0

試試這個

console.log(obj.NPI[0].NPI); 
console.log(obj.NPI[0].EntityType); 
//etc 

你的結構是這樣的

{// Start of object 
    "NPI": //First element, access it as obj.NPI 
     [ // NPI is an array 
     { // First element of the array is an object 
      "NPI": "123456789", // Then access each element of this object using dot notation 
      "EntityType": "Individual", 
      ................................