typescript axios 给了我 JSON 对象,但无法解析为 Javascript 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48119305/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
axios gives me JSON object, but can't parse to Javascript object
提问by cmbo
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. Cool. For my fake data I'm using JSONplaceholder. When I parse, what is returned is [object Object] (see link to image at bottom). What am I doing incorrectly? Eventually I'd like to pull specific data out, like info.name, and display the name.
后端为我提供了一个 JSON 对象数组,我想将这些对象解析为 Javascript 对象。凉爽的。对于我的假数据,我使用的是 JSONplaceholder。当我解析时,返回的是 [object Object](见底部图像链接)。我做错了什么?最终我想提取特定数据,如 info.name,并显示名称。
test.ts
测试.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
测试.html
<template>
<pre style="margin-top: 200px">${info}</pre>
<pre style="margin-top: 200px">${infoX}</pre>
</template>
回答by cmbo
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
测试.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
测试.html
<template>
<ul>
<li repeat.for="info of infos">
Name: ${info.name}
</li>
</ul>
</template>