我正在 React 中从 MySQL 数据库获取数据。 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
})
最佳答案
response.data
不是有效的 JSON 字符串。您可以尝试:
const response = {
"id": 1,
"url": "asd2q13",
"data": "{name: \"Marie\", answers:[\"1\", \"3\", \"0\"]}"
}
console.log(eval('(' + response.data + ')'))
或者更好:
const response = {
"id": 1,
"url": "asd2q13",
"data": "{name: \"Marie\", answers:[\"1\", \"3\", \"0\"]}"
}
function looseJsonParse(obj) {
return Function('"use strict";return (' + obj + ')')();
}
console.log(looseJsonParse(response.data))
但是,
Warning: Executing JavaScript from a string is an enormous security risk. It is far too easy for a bad actor to run arbitrary code when you use
eval()
. See Never use eval()!, below.
我建议您在后端正确序列化数据
。我认为MySQL数据库驱动程序可以做到这一点。另请参阅Parsing JSON (converting strings to JavaScript objects)
关于javascript - React 中的 JSON 解析嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69922516/