2015-09-20 71 views
0

我有一個json輸出值返回未定義的問題。返回未定義值的JSON

JSON:

[ { ID: 2, user: 'ngx.daniel', password: 'password', admin: 'F' } ] 

CODE:

console.log(res); 
res = JSON.stringify(res); 
console.log(res); 
var user = {}; 
user.user = res.user; 
user.password = res.password; 
user.admin = res.admin; 
console.log(user); 

OUTPUT:

[ RowDataPacket { ID: 2, user: 'ngx.daniel', password: 'password', admin: 'F' } ] 
[ { ID: 2, user: 'ngx.daniel', password: 'password', admin: 'F' } ] 
{ user: undefined, password: undefined, admin: undefined } 
+3

'JSON.stringify'返回一個字符串。你爲什麼期望一個字符串擁有'user'屬性? – SLaks

+1

@turbopipp:這沒有什麼區別。 – SLaks

+0

JSON喜歡對象中的字符串,從我記得 – turbopipp

回答

3

有幾件事情。如果這是你的json:

[ RowDataPacket { ID: 2, user: 'ngx.daniel', password: 'password', admin: 'F' } ] 

你不需要將它串聯起來。當你將它串起來時,你可以將你的對象變成一個字符串。然後嘗試訪問它沒有的字符串屬性。
1 - 刪除字符串化
2 - 這是一個數組,它與RowPacketData對象一起返回,這也是無效的json。
3 - 要訪問數組中的對象,您需要先訪問索引。所以它應該是這樣的

(如果res = [ { ID: 2, user: 'ngx.daniel', password: '[email protected]#', admin: 'F' }]

var user = {}; 
user.user = res[0].user; 
user.password = res[0].password; 
user.admin = res[0].admin; 
0

的響應可以明顯是由多個項目(RowDataPackets)的。您可以通過索引0獲得第一和沒有必要字符串化的反應:

console.log(res); 
var user = {}; 
user.user = res[0].user; 
user.password = res[0].password; 
user.admin = res[0].admin; 
console.log(user); 

它打印

對象{用戶=「ngx.daniel」,密碼=「根_ $! @#「,admin =」F「}