-1

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 "{\r\n\r\n}"

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

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

because of "\r\n", I tried {{parseJson(test.json)}}

 parseJson(str:string):any{
    console.log(str);
    console.log(str.includes("\r\n")); // 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>                   
D999_X
  • 3
  • 5

2 Answers2

0

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' } };
}
John Woodruff
  • 1,608
  • 16
  • 29
  • Hello, when I add {{test.testJSON | json}} , the html shows as ```"{\r\n \"id\" : \"80\",\r\n \"amount\" : \"120\",\r\n \}" ``` – D999_X Apr 17 '23 at 14:20
0

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

D999_X
  • 3
  • 5