0

In my app I have an API call that returns a JSON with the following (simplified) structure:

{
   "prop1": "foo",
   "prop2": "bar",
   "details": "{\"title\": \"Sample Konfabulator Widget\", \"name\": \"main_window\", \"width\": 500, \"height\": 500}"
}

The details prop contains a large stringified JSON that is read from the database.

Now, in the User Interface I want to display a prettified and formatted version of the details prop, something like:

enter image description here

I've tried it with:

<pre>{{ apiResponse.details }}</pre>

But the entire JSON is displayed in a single line.

The code I've tried is: https://stackblitz.com/edit/angular-pkfgvf?file=src%2Fapp%2Fapp.component.ts

Thanks!

andreivictor
  • 7,628
  • 3
  • 48
  • 75
  • Take a look at [this question](https://stackoverflow.com/q/37308420/1009922). – ConnorsFan Apr 13 '20 at 15:27
  • 2
    in your demo you need to parse the string into json, you can wrap the string with `JSON.parse` https://stackblitz.com/edit/angular-nwjaxc?file=src/app/app.component.ts – Juan Apr 13 '20 at 15:36
  • @Juan, thanks! a little bit weird, at first thought, that I have to parse the original string into an object, then pass this object to the `json` pipe, that re-converts it to a string, that is well formatted. but now I understood why... – andreivictor Apr 13 '20 at 15:44

2 Answers2

1

Your details it's not a json object and that's why it's not being parsed, you will need to wrap it in JSON.parse()

details: JSON.parse("{\"title\": \"Sample Konfabulator Widget\", \"name\": \"main_window\", \"width\": 500, \"height\": 500}")

and you can now display it using the json pipe

{{ apiResponse.details | json  }}

Updated Demo

Juan
  • 4,910
  • 3
  • 37
  • 46
  • I've put it in a try / catch block, just to make sure that the app doesn't break: https://stackblitz.com/edit/angular-aqzkau?file=src%2Fapp%2Fapp.component.ts – andreivictor Apr 13 '20 at 16:03
  • 1
    @Juan - After parsing the JSON string, the resulting object is displayed with `{{ apiResponse.details | json }}`. I suggest mentioning it in the answer. – ConnorsFan Apr 13 '20 at 16:07
0

If you don't want to use JSON.parse() in you object directly, so you can create pipe that convert string object in to json.

rajratna maitry
  • 378
  • 3
  • 9