【发布时间】:2021-12-23 14:20:39
【问题描述】:
我正在从 MySQL 数据库中获取 React 中的数据。 MySQL 自动转义我的值,包括嵌套对象。我在顶层使用 .json() 函数,但我无法在子层使用它,JSON.parse(response[0].data) 也无法使用。
正确的做法是什么?
fetch(`http://localhost:3000/getQuiz${window.location.pathname}`, requestOptions)
.then(response => response.json())
.then(response => {
console.log(response)
// {
// "id": 1,
// "url": "asd2q13",
// "data": "{name: \"Marie\", answers:[\"1\", \"3\", \"0\"]}"
// }
console.log(typeof response)
// object
console.log(response[0].data)
// {name: "Marie", answers:["1", "3", "0"]}
console.log(typeof response[0].data)
// string
console.log(response[0].data.name)
// undefined
})
【问题讨论】:
-
我认为这是因为它不喜欢
{name: "Marie", answers:["1", "3", "0"]}在属性名称周围缺少引号。 JSON spec 指定对象成员为 字符串名称-分隔符值(第 2.2 节),它进一步说明 字符串以引号开始和结束(第 2.5 节)。所以存储在 data 属性中的“JSON”中的属性名称是无效的。 JSON.parse() 会抛出错误吗?
标签: javascript reactjs json fetch