【发布时间】:2021-10-19 08:02:47
【问题描述】:
我想将数据传输到数组中,我的 api 响应是like this
在 api 响应中有:locationslist :"[\"Location 2\",\"Location 2\"]"
如何在 react Js 中得到干净的响应?
我也在尝试JSON.parse() 它给了我错误
【问题讨论】:
-
你遇到了什么错误?
我想将数据传输到数组中,我的 api 响应是like this
在 api 响应中有:locationslist :"[\"Location 2\",\"Location 2\"]"
如何在 react Js 中得到干净的响应?
我也在尝试JSON.parse() 它给了我错误
【问题讨论】:
这样就可以了:
const localtionList = "[\"Location 2\",\"Location 2\"]";
console.log(JSON.parse(localtionList))
【讨论】:
您收到错误是因为您尝试使用 JSON.parse() 解析 JavaScript 对象。要解决此问题,您需要将 JSON 字符串传递给 JSON.parse() 方法,如下所示:
const something = {
locationslist :"[\"Location 2\",\"Location 2\"]"
};
// This code will give error
console.log(JSON.parse(something));
// This will work fine because locationslist
// holds a JSON string
console.log(JSON.parse(something.locationslist));
【讨论】: