我正在從 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
})
uj5u.com熱心網友回復:
該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))
但,
警告:從字串執行 JavaScript 存在巨大的安全風險。當您使用
eval(). 請參閱永遠不要使用 eval()!, 以下。
我建議您data在后端正確序列化。我認為 MySQL 資料庫驅動程式可以做到這一點。另請參閱決議 JSON(將字串轉換為 JavaScript 物件)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/355609.html
標籤:javascript 反应 json 拿来
上一篇:并排顯示折疊部分
下一篇:如何根據物件的特定值更新物件?
