簡體   English   中英

JSON.parse 返回 [Object Object] 而不是值

[英]JSON.parse returning [Object Object] instead of value

我的 API 返回 JSON 值,如

[{"UserName":"xxx","Rolename":"yyy"}]

我需要UsernameRoleName值分別我試過 JSON.parse 但它返回 [Object Object] 請幫助我提前謝謝

請考慮以下事項:

 var str = '[{"UserName":"xxx","Rolename":"yyy"}]'; // your response in a string var parsed = JSON.parse(str); // an *array* that contains the user var user = parsed[0]; // a simple user console.log(user.UserName); // you'll get xxx console.log(user.Rolename); // you'll get yyy

你有一個array 然后需要首先獲取0th元素

這將工作

 let unps = JSON.parse('[{"UserName":"xxx","Rolename":"yyy"}]')[0] console.log(unps.UserName, unps.Rolename);

如果您的數據是一個字符串,那么您需要使用JSON.parse()解析它,否則您不需要,您只需按原樣訪問它。

 // if data is not in string format const data = [{"UserName":"xxx","Rolename":"yyy"}]; const username = data[0].UserName const rolename = data[0].Rolename console.log(username) console.log(rolename) // if data is in string format const strData = JSON.parse('[{"UserName":"xxx","Rolename":"yyy"}]'); const Username = strData[0].UserName const Rolename = strData[0].Rolename console.log(Username) console.log(Rolename)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM