代码之家  ›  专栏  ›  技术社区  ›  cmbo

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

  •  2
  • cmbo  · 技术社区  · 7 年前

    我一直在试图弄明白这一点,但不知道我做错了什么。我还不熟悉Aurelia、Typescript和Axios。

    后端为我提供了一个JSON对象数组,我想将其解析为Javascript对象。凉的对于我的假数据,我使用了JSONplaceholder。解析时,返回的是[对象对象](请参阅底部图像链接)。我做错了什么?最后,我想拿出具体的数据,比如信息。名称,并显示名称。

    测验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>
    

    screenshot of what the console log and view displays

    1 回复  |  直到 7 年前
        1
  •  1
  •   cmbo    7 年前

    以下链接帮助我澄清了一些困惑: simple explanation of JSON.parse and JSON.stringify

    然后,在我迭代数组的注释中听取Jame的建议,并从服务器返回数据。

    测验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>