调用Web API返回[object object],如何获取正确JSON格式数据?
解决API响应显示[object Object]并正确获取JSON数据的问题
问题根源
你遇到的[object Object]是因为直接将对象与字符串拼接时,JavaScript会默认把对象转为[object Object]字符串;同时代码里错误调用了responseJSON.stringify和item.stringify——JSON.stringify()是全局方法,不是对象的内置属性。
修正步骤
- 正确打印对象:不要用
+拼接对象,改用逗号分隔让控制台直接展示对象结构,或者用JSON.stringify()将对象转为可阅读的字符串。 - 修正JSON序列化调用:把
responseJSON.stringify改为JSON.stringify(responseJSON),item.stringify改为JSON.stringify(item)。 - (可选)优化Promise嵌套:用
async/await替代多层then,让代码更简洁易维护。
修正后的代码
// 方式1:修正原Promise写法 const userList: ISuggestionItem[] = []; this.props.context.aadHttpClientFactory .getClient('xxxxxx-xxx-xxx-xxx-xxxx') .then((client: AadHttpClient): void => { client .get('https://xxxxx.azurewebsites.net/api/xxxxxx?userEmail=xxxxx.onmicrosoft.com', AadHttpClient.configurations.v1) .then((response: HttpClientResponse) => { // 用逗号分隔打印,直接查看response对象 console.log("First hit", response); response.json().then((responseJSON: any) => { // 用JSON.stringify序列化对象 console.log("Second hit", JSON.stringify(responseJSON)); responseJSON.map(function(item: any) { console.log("third hit", JSON.stringify(item)); userList.push({ key: item.Test1, displayValue: item.Test2, searchValue: item.Test3 }); }); }); }); });
// 方式2:用async/await优化(更推荐) const fetchUserList = async () => { const userList: ISuggestionItem[] = []; try { const client = await this.props.context.aadHttpClientFactory.getClient('xxxxxx-xxx-xxx-xxx-xxxx'); const response = await client.get('https://xxxxx.azurewebsites.net/api/xxxxxx?userEmail=xxxxx.onmicrosoft.com', AadHttpClient.configurations.v1); console.log("First hit", response); const responseJSON = await response.json(); console.log("Second hit", JSON.stringify(responseJSON)); responseJSON.forEach((item: any) => { console.log("third hit", JSON.stringify(item)); userList.push({ key: item.Test1, displayValue: item.Test2, searchValue: item.Test3 }); }); } catch (error) { console.error('请求失败:', error); } }; fetchUserList();
验证效果
修改后,控制台会打印出格式化的JSON字符串,或者直接展示对象结构,你可以清晰看到API返回的具体数据,同时userList也能正确填充数据。
内容的提问来源于stack exchange,提问作者Ashok
相关产品推荐
相关产品推荐

