首页 > 解决方案 > 从字符串中获取对象,其中字符串包含数组中的对象

问题描述

以下是我从服务器获取的数据:

let data = aa[0].innerHTML.trim();

数据:

[        
  {
    "userid" : "3455535",
    "roll_number" : "8845",
    "Attributes" :  {
    },
    "status" : "Fail",
    "barCode" : '5774777858'
  }
]

这个数据是typeof string

我想从这个字符串中提取整个对象,我尝试使用 JSON.parse 但它的抛出错误。

console.log(JSON.parse(data))

SyntaxError: Unexpected token ' in JSON at position 326

我也试过(用 '' 替换 [ & ] 然后修剪,但这也不起作用)

console.log(data.replace(/[|]/, ''))

让我知道如何提取数据。

标签: javascriptstringecmascript-6

解决方案


您需要在 JSON 响应中'替换所有出现的 。"

data = data.replace(/\'/g, '"')

推荐阅读