1

I'm trying to print a JSON (link to the JSON) in an html file.

JSON:

{
  "ricette": {
    "FRIGGITRICI": {
      "Alici": [
        [
          {"500": "scongelamento"}
        ],
        [
          {"60": "nada"}
        ]
      ],
      "Baccalà": [
        [
          {"500": "scongelamento"}
        ],
        [
          {"210": "immerso"},
          {"210": "cestello su"},
          {"30": "immerso"}
        ]
      ]
    },
    "GRIGLIA": {
      "Baccalà": [
        [
          {"500": "scongelamento"}
        ],
        [
          {"210": "immerso"},
          {"210": "cestello su"},
          {"30": "immerso"}
        ]
      ]
    }
  }
}

I've fetched it and saved in a variable:

export class DatiService {
  fileJson: JSON;

  constructor() { }

  private datiUrl = 'https://api.myjson.com/bins/zbfh5';

  async getDati(){
    await fetch(this.datiUrl)
    .then(res => res.json())
    .then((out) => {
      this.fileJson=out;
    });
    console.log(this.fileJson);
  };
}

How can i print it in the html code? Can i just use de "." to enter in its fields? Or it's more complicated?

2 Answers 2

5

You can use the JsonPipe in your template.

{{fileJson | json}}

If you want to print a specific part you can navigate via . deeper into the object structure.

{{fileJson.ricette.FRIGGITRICI | json}}

If you want to print a primitiv value interpolation is enough and no json pipe is needed.

{{fileJson.version}}

UPDATE

Did you called your getDati function? Add an ngOnInit Lifecycle Hook and call it there. Here is an working stackblitz sample.

I just realized it's a service in your sample code. Take the service and inject it into a component and call it there.

Sign up to request clarification or add additional context in comments.

2 Comments

Nothing happens in my code... fileJson and the fetch aren't in the html file
And i updated the answer with a full working sample.
-2

We can use pre tag to view JSON data in HTML Pass your JSON in var data. And Set pre tag in HTML body.

var data = {Your JSON Object}
$("#json").innerHTML = JSON.stringify(data, undefined, 2);
<pre id="json"></pre>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.