To read (and parse) JSON data from HTML <script>
tag, you must:
- Set the
<script>
tag'stype
attribute to "application/json
"; - Select the
<script>
HTML element via JavaScript and access the JSON data string, for example, by using theNode.textContent
property; - 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.