Home > Back-end >  Is it possible to output a JSON object row by row in Angular?
Is it possible to output a JSON object row by row in Angular?

Time:12-04

I have a field "properties" in my table(data type: text). In this field there is a JSON object. Now I want to output it in Angular in a reasonable way as I have shown below. Currently only the JSON format is displayed.

There must be a way to display the attributes of a JSON format row by row, right?

"properties": "{'width': 4, 'height': 14, 'count': 10, 'qm': 63, 'loc_x': 0, 'loc_y': 0, 'loc_x': 1}",
width: 4
height: 14
count: 10
qm: 63
loc_x: 0
loc_y: 0
loc_x: 1

UDATE 1:

<div *ngFor="let property of properties | keyvalue">
                    {{property.key}}: {{property.value}}
                  </div>

UPDATE 2:

This is my JSON from the Backend

{
    "id": 1,
    "formId": 1,
    "properties": "{'width': 4, 'height': 14, 'count': 10, 'qm': 63, 'loc_x': 0, 'loc_y': 0, 'loc_x': 1}",
    "components": [
        {
            "id": 1,
            "shapeId": 1,
            "properties": "{'width': 4, 'height': 14, 'count': 10, 'qm': 63, 'loc_x': 0, 'loc_y': 0, 'loc_x': 1}",
            "shapeComponentMaterials": [
                {
                    "id": 1,
                    "componentId": 1,

                },
                {
                    "id": 15,
                    "componentId": 1,

                }
            ]
        },
        {
            "id": 11,
            "shapeId": 1,
            "properties": "{'width': 4, 'height': 14, 'count': 10, 'qm': 63, 'loc_x': 0, 'loc_y': 0, 'loc_x': 1}",
            "shapeComponentMaterials": [
                {
                    "id": 11,
                    "componentId": 11,
                }
            ]
        }
    ]
}

This is my shape.ts

export interface Shape { 
   
    id?: number;
    formId: number;
    properties?: string;
    components?: Array<Component>;
}


CodePudding user response:

You can make use of Angular's KeyValuePipe to display the data in the desired format:

<div *ngFor="let property of properties | keyvalue">
{{property.key}}:{{property.value}}
</div>

UPDATE - Extending answer as per request

As you have updated your question with the exact API response, here's the method to access the properties property to display it in HTML as required:

accessingProperties = JSON.parse(this.valueFromAPI.properties.replace(/'/g, '"'));

Here's a Stackblitz with this example in live.

  • Related