How to Read JSON Data From HTML script Tag Using JavaScript?

To read (and parse) JSON data from HTML <script> tag, you must:

  1. Set the <script> tag's type attribute to "application/json";
  2. Select the <script> HTML element via JavaScript and access the JSON data string, for example, by using the Node.textContent property;
  3. Parse the JSON data string using the JSON.parse() method.

For example, let's suppose you have the following JSON data in HTML <script> tag:

<script id="json-data" type="application/json">
  "name": "John Doe",
  "age": 27

You can access it and parse it in the following way:

const jsonStr = document.getElementById('json-data').textContent;
const jsonData = JSON.parse(jsonStr);

console.log(jsonData); // {"age": 27, "name": "John Doe"}

It is important to note that this method is not suitable for large amounts of data, as it can affect the performance of the page. In that instance, it might be better to use an HTTP request to retrieve JSON data from the server.

Hope you found this post useful. It was published . Please show your love and support by sharing this post.