javascript - React 中的 JSON 解析嵌套对象

标签 javascript reactjs json fetch

我正在 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/

相关文章:

android - 应用在元数据中包含对 Android 的引用

javascript - 为什么 Appbase 在返回正确的项目之前返回 'undefined'?

javascript - 使用 Angular 搜索 JSON

json - 如何在 terraform 中定义基于 AWS IAM 属性的访问控制

javascript - 了解嵌套回调和作用域?

javascript - 帮助 jquery slider 范围选项

javascript - 在 Javascript 中嵌套对象 - 匿名不是函数错误

javascript - 当子组件调用方法时,父引用为 null - ReactJS

javascript - Threejs ray cast 获取交点坐标

javascript - 使用 typescript 将 Json 转换为数组 Angular 2 js