网站搜索

axios 给我 JSON 对象,但无法解析成 Javascript 对象


我一直在尝试弄清楚这一点,但不知道自己哪里做错了。我对 Aurelia、Typescript 和 Axios 也不熟悉。

后端给我一个 JSON 对象数组,我想把它解析成 JavaScript 对象。很好。对于我的假数据,我使用的是 JSONplaceholder。当我解析时,返回的是 [object Object](见底部图片链接)。我哪里做错了?最终我想提取特定数据,比如 info.name,并显示名称。

test.ts

import axios from 'axios';
const apiURL = 'https://jsonplaceholder.typicode.com/users';

declare var $: any;


export class Test {
    info: string;
    infoX: string;
    public constructor () {
      axios.get(apiURL)
        .then(response => {
          this.info = JSON.stringify(response.data)
          this.infoX = JSON.parse(this.info);
          console.log(this.info);
          console.log(this.infoX);
        })
        .catch(error => console.log(error));
    }
}

测试.html

<template>
  <pre style="margin-top: 200px">${info}</pre>
  <pre style="margin-top: 200px">${infoX}</pre>
</template>

控制台日志和视图显示的截图

答案#1

以下链接帮助我理清了一些困惑:JSON.parse 和 JSON.stringify 的简单解释

然后听从评论中詹姆斯的建议,我对数组进行了迭代,并从服务器返回了数据。

test.ts

import axios from 'axios';
const apiURL = 'https://jsonplaceholder.typicode.com/users';

export class Data {
    infos: string;
    public constructor () {
      axios.get(apiURL)
        .then(response => {
          this.infos = response.data;
          console.log(this.infos);
        })
        .catch(error => console.log(error));
    }
}

测试.html

<template>
    <ul>
        <li repeat.for="info of infos">
          Name: ${info.name}
        </li>
    </ul>
</template>