Html/JavaScript: How to Access Json Data Loaded in a Script Tag With Src Set

HTML/Javascript: how to access JSON data loaded in a script tag with src set

You can't load JSON like that, sorry.

I know you're thinking "why I can't I just use src here? I've seen stuff like this...":

<script id="myJson" type="application/json">
{
name: 'Foo'
}
</script>

<script type="text/javascript">
$(function() {
var x = JSON.parse($('#myJson').html());
alert(x.name); //Foo
});
</script>

... well to put it simply, that was just the script tag being "abused" as a data holder. You can do that with all sorts of data. For example, a lot of templating engines leverage script tags to hold templates.

You have a short list of options to load your JSON from a remote file:

  1. Use $.get('your.json') or some other such AJAX method.
  2. Write a file that sets a global variable to your json. (seems hokey).
  3. Pull it into an invisible iframe, then scrape the contents of that after it's loaded (I call this "1997 mode")
  4. Consult a voodoo priest.

Final point:

Remote JSON Request after page loads is also not an option, in case you want to suggest that.

... that doesn't make sense. The difference between an AJAX request and a request sent by the browser while processing your <script src=""> is essentially nothing. They'll both be doing a GET on the resource. HTTP doesn't care if it's done because of a script tag or an AJAX call, and neither will your server.

Loading a JSON file via a script tag

What you can do is set a global variable within your external file:

window.myJSON = { ... };

Then your other code can access that data via window.myJSON.

I'm not sure how browsers parse .json files so you may need to change the extension to .js.

How can I read a JSON in the script-tag from JavaScript?

I would change the script declaration to this:

<script id="data" type="application/json">{"org": 10, "items":["one","two"]}</script>

Note type and id fields. After that

var data = JSON.parse(document.getElementById('data').textContent);

will work just fine in all browsers.

The type="application/json" is needed to prevent browser from parsing it while loading.

And the reason why we use textContent instead of innerHTML or innerText to read the raw Json text is because innerHTML tries to parse the contents as HTML which will lead to slower performance and possible parsing bugs and XSS attacks, and innerText won't grab the raw text and will instead look for human-visible text, whereas textContent grabs the pure text as-is (which is what you want). See https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent for more details about why innerHTML and innerText are bad.

How to read json file correctly using only JavaScript

You can't load JSON through a script element. Instead, in your script.js, you can fetch it:

fetch("data.json")
.then(response => {
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
return response.json();
})
.then(data => {
// Use the data here, it's been parsed
})
.catch(error => {
// Handle/report error here
});

Parse JSON data inside from occurrence of script tag using SimpleHtmlDom - PHP

If you specify the index of the instance you want, you only get that element back and not a list, so the loop isn't required (in fact is the problem)...

$json = $html->find('script[type="application/ld+json"]',0);
echo $json->innertext;

Just for reference, the code from find()...

    // return nth-element or array
if (is_null($idx)) return $found;
else if ($idx<0) $idx = count($found) + $idx;
return (isset($found[$idx])) ? $found[$idx] : null;

Reading JSON from script in Javascript

The JSON isn't included. JSON is not a script and browsers have no idea what to do when you try to load it using a script element. All that script element is doing is sitting in the DOM. Therefore:

  1. Find the script element by its id
  2. Get the src attribute from it
  3. Use XMLHttpRequest to request the data


Related Topics



Leave a reply



Submit