const dataStr = "{msg=infos.verifyAbnormal, code=601, data=[{fieldNameCn=纬度, fieldName=LATITUDE, messageGrade=2, messageTitleCn=超出范围, messageTitle=Out of the range, tipsCn=不能超出以下范围: (1)度:0<= ~ <90 (2)分:0<= ~ <60, tipsEn=Could not out of the range: (1)Degree:0<= ~ <90 (2)Minute:0<= ~ <60},{fieldNameCn=纬度, fieldName=LATITUDE, messageGrade=2, messageTitleCn=超出范围, messageTitle=Out of the range, tipsCn=不能超出以下范围: (1)度:0<= ~ <90 (2)分:0<= ~ <60, tipsEn=Could not out of the range: (1)Degree:0<= ~ <90 (2)Minute:0<= ~ <60}]}";
后端给了个这数据,怎么转换成前端可用的 一个数组 字段 msg: '',一个code:,一个data []这种格式data 可能包含有很多对象
无能为力,让后端传标准JSON格式
【以下回答由 GPT 生成】
首先,我们可以使用 JavaScript 的字符串处理函数来处理这个字符串数据。我们可以先移除dataStr开头和结尾的<p>
标签,然后使用eval()
函数将字符串转换为一个 JavaScript 对象。接下来,我们可以在获取到的对象中提取出我们需要的字段msg、code和data。
以下是具体的代码实现:
const dataStr = `<p>const data = "{msg=infos.verifyAbnormal, code=601, data=[{fieldNameCn=纬度, fieldName=LATITUDE, messageGrade=2, messageTitleCn=超出范围, messageTitle=Out of the range, tipsCn=不能超出以下范围: (1)度:0<= ~ <90 (2)分:0<= ~ <60, tipsEn=Could not out of the range: (1)Degree:0<= ~ <90 (2)Minute:0<= ~ <60},{fieldNameCn=纬度, fieldName=LATITUDE, messageGrade=2, messageTitleCn=超出范围, messageTitle=Out of the range, tipsCn=不能超出以下范围: (1)度:0<= ~ <90 (2)分:0<= ~ <60, tipsEn=Could not out of the range: (1)Degree:0<= ~ <90 (2)Minute:0<= ~ <60}]}"</p>`;
// 移除<p>标签
const cleanDataStr = dataStr.replace(/<p>/g, '').replace(/<\/p>/g, '');
// 使用eval()将字符串转换为对象
const dataObj = eval(cleanDataStr);
// 提取msg、code和data字段
const { msg, code, data } = dataObj;
console.log(msg); // 输出:infos.verifyAbnormal
console.log(code); // 输出:601
console.log(data); // 输出:包含多个对象的数组
注意:使用eval()
函数来解析字符串时存在安全风险,请确保你获取的字符串数据是可信的,并且仅在确定是安全的情况下使用此方法。