【问题标题】:axios gives me JSON object, but can't parse to Javascript objectaxios 给了我 JSON 对象,但无法解析为 Javascript 对象
【发布时间】:2018-06-15 14:27:43
【问题描述】:

我一直在努力解决这个问题,但不知道我做错了什么。我也是 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));
    }
}

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

【问题讨论】:

  • 不,后端给你一个 JSON 字符串——所以在你的响应处理程序中去掉 JSON.stringify。现在,假设您在 javascript 中有一个对象数组,并尝试将其设置为某个 div 的 html - 您将得到 [[Object object],[Object object]...]。您需要对数组进行迭代,从对象中提取各种属性并显示它们。
  • 你的问题不在于解析,而在于打印。 ${infoX} 将数组转换为与JSON.stringify不同的字符串
  • @James 感谢您的回复。你能为我澄清一些事情吗?如果后端给了我一个字符串,对象数组是否必须用引号引起来?
  • 通常用于将本机对象或数组转换为 JSON 的后端函数会处理所有引号,但看起来您正在发送/接收 JSON 就好了。
  • @James,感谢您的帮助和澄清。为我指明了正确的方向。关键是像你提到的那样迭代。并更好地理解 JSON.parse 和 JSON.stringify。

标签: javascript json typescript aurelia axios


【解决方案1】:

以下链接有助于消除我的一些困惑:simple explanation of JSON.parse and JSON.stringify

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

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

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

【讨论】:

    猜你喜欢
    • 2016-05-07
    • 1970-01-01
    • 2021-06-07
    • 2020-01-08
    • 1970-01-01
    • 2015-01-25
    • 2014-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多