简体   繁体   English

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

[英]axios gives me JSON object, but can't parse to Javascript object

I've been trying to figure this out, and don't know what I'm doing incorrectly. 我一直在试图找出答案,但不知道我在做什么错。 I'm also new to Aurelia, Typescript, and Axios. 我也是Aurelia,Typescript和Axios的新手。

The backend gives me a JSON array of objects that I want to parse into Javascript Objects. 后端为我提供了一个要解析为Javascript对象的对象的JSON数组。 Cool. 凉。 For my fake data I'm using JSONplaceholder. 对于我的虚假数据,我正在使用JSONplaceholder。 When I parse, what is returned is [object Object] (see link to image at bottom). 当我解析时,返回的是[object Object](请参阅底部的图像链接)。 What am I doing incorrectly? 我做错了什么? Eventually I'd like to pull specific data out, like info.name, and display the name. 最终,我想提取特定数据,例如info.name,并显示名称。

test.ts 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));
    }
}

test.html 的test.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 控制台日志和视图显示的屏幕截图

The following link helped clear up some confusion I was having: simple explanation of JSON.parse and JSON.stringify 以下链接有助于消除我的困惑: JSON.parse和JSON.stringify的简单说明

Then listening to Jame's advice in the comments I iterated over the array, and returned the data from server. 然后在迭代数组的注释中听Jame的建议,并从服务器返回数据。

test.ts 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));
    }
}

test.html 的test.html

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM