You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用Web API返回[object object],如何获取正确JSON格式数据?

解决API响应显示[object Object]并正确获取JSON数据的问题

问题根源

你遇到的[object Object]是因为直接将对象与字符串拼接时,JavaScript会默认把对象转为[object Object]字符串;同时代码里错误调用了responseJSON.stringify和item.stringify——JSON.stringify()是全局方法,不是对象的内置属性。

修正步骤

  1. 正确打印对象:不要用+拼接对象,改用逗号分隔让控制台直接展示对象结构,或者用JSON.stringify()将对象转为可阅读的字符串。
  2. 修正JSON序列化调用:把responseJSON.stringify改为JSON.stringify(responseJSON),item.stringify改为JSON.stringify(item)。
  3. (可选)优化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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 13:22:33