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

Angular如何将存储为文本的JSON对象属性逐行格式化输出

问题根因

你之前的写法不生效的核心原因是properties字段是字符串类型,并非可遍历的JSON对象,Angular的keyvalue管道无法直接处理字符串类型的JSON内容,且你示例中的JSON字符串用了单引号,不符合标准JSON的双引号规范,直接解析会报错。


解决方案

以下提供两种常用实现方式,可根据业务场景选择:

方案1:拿到数据后预处理转换(性能更优)

适合数据仅在少数地方展示的场景,提前把字符串转成可遍历的对象。

  1. 先修改Shape接口,新增解析后的对象字段:
export interface Shape { 
  id?: number;
  formId: number;
  properties?: string;
  parsedProperties?: Record<string, any>; // 存储解析后的JSON对象
  components?: Array<Component & {parsedProperties?: Record<string, any>}>;
}
  1. 拿到后端返回数据后统一做转换处理:
processShapeData(rawShape: Shape): Shape {
  // 处理根层级properties
  if (rawShape.properties) {
    // 把单引号替换为双引号,兼容非标准JSON格式
    const validJsonStr = rawShape.properties.replace(/'/g, '"');
    rawShape.parsedProperties = JSON.parse(validJsonStr);
  }
  // 处理子组件内的properties
  if (rawShape.components?.length) {
    rawShape.components = rawShape.components.map(comp => {
      if (comp.properties) {
        const validJsonStr = comp.properties.replace(/'/g, '"');
        comp.parsedProperties = JSON.parse(validJsonStr);
      }
      return comp;
    })
  }
  return rawShape;
}
  1. 模板中直接遍历解析后的对象:
<!-- 遍历根层级properties -->
<div *ngFor="let item of shape.parsedProperties | keyvalue">
  {{item.key}}: {{item.value}}
</div>

<!-- 遍历子组件properties -->
<div *ngFor="let comp of shape.components">
  <div *ngFor="let item of comp.parsedProperties | keyvalue">
    {{item.key}}: {{item.value}}
  </div>
</div>

方案2:自定义转换管道(复用性更强)

适合多处需要展示该字段的场景,无需提前处理数据,直接在模板中使用。

  1. 生成自定义管道:在项目终端执行ng generate pipe parseJson
  2. 编写管道逻辑:
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'parseJson',
  pure: true // 开启纯管道,只有输入值变化时才会重新计算
})
export class ParseJsonPipe implements PipeTransform {
  transform(value: string): Record<string, any> | null {
    if (!value) return null;
    try {
      const validJsonStr = value.replace(/'/g, '"');
      return JSON.parse(validJsonStr);
    } catch (err) {
      console.error('properties字段解析失败:', err);
      return null;
    }
  }
}
  1. 模板中直接使用管道:
<div *ngFor="let property of (shape.properties | parseJson) | keyvalue">
  {{property.key}}: {{property.value}}
</div>

注意事项

如果你的业务需要保留JSON字符串中重复key(比如示例里的两个loc_x),JSON.parse默认会保留最后一个值,此时需要自定义简单的字符串分割逻辑处理重复键,无需依赖标准JSON解析方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 11:54:03