skip to Main Content

There is test data shows on frontend

{"id" : "49", "users" : {"type" : "test"}}

and at angular html file, test is list which get from api service call

get().subscribe((resp)=>{
  this.test = resp["data"];
})
<td>{{test.name}}</td>
<td>{{test.json}}</td>

what i am want is make test shows as format

{
 "id" : "49", 
 "users" : {"type" : "test"}
}

I tried add {{test.json|json}} use json pipe, but html shows
"{rnrn}"

also I add parseJson at component, {{parseJson(test.json)}}, html get [object Object]

parseJson(str:string):any{
   return JSON.parse(str);
 }

because of "rn", I tried {{parseJson(test.json)}}

 parseJson(str:string):any{
    console.log(str);
    console.log(str.includes("rn")); // it's true
}

html at console shows

{
 "id" : "49", 
 "users" : {"type" : "test"}
}

but do not have line break at html for

<td>{{parseJson(test.json)}}</td>                   

2

Answers


  1. Chosen as BEST ANSWER

    it's format at console, at last I add css style to white-space: pre-line; Line break in HTML with 'n'


  2. To format JSON on an HTML page you can make use of the JsonPipe. You can also wrap it in a pre tag to maintain the correct formatting. Here is a StackBlitz showing how it works.

    @Component({
      selector: 'my-app',
      standalone: true,
      imports: [CommonModule],
      template: `
        <h1>JSON Formatting</h1>
        <pre>
    {{jsonData | json}}
        </pre>
      `,
    })
    export class App {
      jsonData = { id: '49', users: { type: 'test' } };
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search