You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将API响应中string类型的oldRecord、newRecord转JSON并展示到表格

解决方法

错误原因

你直接对res.apiData执行JSON.parse报错,是因为res.apiData本身已经是接口返回的解析完成的数组结构,无需整体转JSON,只有数组元素内的oldRecord、newRecord两个字段的值是JSON字符串,需要单独解析。

修正后的逻辑代码

this.searchPendings = this.service.get(obj).subscribe(res => {
  // 遍历处理每一条数据
  this.dataSource = res.apiData.map(recordItem => {
    let parsedOld = {}
    let parsedNew = {}
    // 加try catch避免JSON格式错误导致页面崩溃
    try {
      // 单独解析两个字段的JSON字符串
      parsedOld = JSON.parse(recordItem.oldRecord)
      parsedNew = JSON.parse(recordItem.newRecord)
    } catch (err) {
      console.error('JSON字段解析失败:', err)
    }
    // 返回合并后的数据,保留原有字段的同时新增解析完成的对象
    return {
      ...recordItem,
      parsedOldRecord: parsedOld,
      parsedNewRecord: parsedNew
    }
  })
})

表格渲染代码(适配Angular框架,匹配你的代码风格)

<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">newRecord</th>
<th style="text-align: left;">oldRecord</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of dataSource">
<td style="text-align: left;">Name: {{item.parsedNewRecord.Name}}</td>
<td style="text-align: left;">Name: {{item.parsedOldRecord.Name}}</td>
</tr>
</tbody>
</table>
</div>

注意事项

你示例中给出的oldRecord字符串末尾存在缺少闭合引号的语法问题("Type": "Feat}应为"Type": "Feat"}),如果实际接口返回确实存在该问题,请先联系后端修正返回格式,或在前端做字符串兼容补全后再执行JSON解析。

内容的提问来源于stack exchange,提问作者XenDex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 14:09:04