2017-10-19 53 views
0

我有一個JSON對象,看起來像這樣。閱讀簡單的JSON對象返回undefined

{ 
    "Manager": "[{\"firstname\":\"Kris\"}],[{\"lastname\":\"test\"}]", 
    "Employee": "[{\"firstname\":\"Nick\"}],[{\"lastname\":\"test\"}]" 
    } 

我正在使用Jquery嘗試讀取我的對象,但似乎我在某種程度上犯了一個錯誤。

JSON.stringify(data[0].Manager.firstname) //returns undefined. 

如何通過JQuery閱讀任何建議將非常感激

請注意我的數據類型是JSON在我的AJAX調用。提前致謝。

+0

是吧'name'或'firstname'? –

+0

對不起,它的名。我編輯了我的問題。 – Kristo

+0

使用'''而不是'\「' –

回答

0

你的JSON有fistName爲您的名字。將它更改爲firstName應該可以解決它。

0

這就是你如何用js來做json。

var data = [{ 
 
    "Manager": { 
 
     "firstname": "Kris", 
 
     "lastname": "test" 
 
    }, 
 
    "Employee": { 
 
     "firstname": "Nick", 
 
     "lastname": "test" 
 
    } 
 
    }, 
 
    { 
 
    "Manager": { 
 
     "firstname": "Kris2222", 
 
     "lastname": "test222" 
 
    }, 
 
    "Employee": { 
 
     "firstname": "Nick222", 
 
     "lastname": "test2222" 
 
    } 
 
    } 
 
]; 
 

 

 

 
console.log(data[0].Manager.firstname); 
 
console.log(data[1].Manager.firstname);

+0

謝謝丹尼爾。我想我需要找出爲什麼我的JSON對象混亂了。我會讓你知道的。 – Kristo

+0

我知道這是一個有效的JSON對象的正確方法,但似乎有一個閱讀Farhad答案的對象。我會明天嘗試一下,然後我會想出一個編輯。 – Kristo

2

這不是有效的JSON "[{\"fistname\":\"Nick\"}],[{\"lastname\":\"test\"}]"

是有效的JSON "[{\"fistname\":\"Nick\"},{\"lastname\":\"test\"}]"

焯芬json online

var obj= {"Manager": "[{\"fistname\":\"Kris\"},{\"lastname\":\"test\"}]","Employee": "[{\"fistname\":\"Nick\"},{\"lastname\":\"test\"}]"}; 
 
    $.each(obj,function(key,value){ 
 
    if(key=='Manager'){ 
 
     var elem=$.parseJSON(value); 
 
     $.each(elem,function(key,value){ 
 
     if(!(typeof value.fistname === "undefined")) 
 
      console.log(value.fistname); 
 
     }); 
 
    } 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>