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.

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.