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

Accessing and parsing JSON data in 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
}
</script>

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

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

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

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.