I have a dynamically generated page where I want to use a static JavaScript and pass it a JSON string as a parameter. I have seen this approach used by Google (see Google's +1 Button: How do they do it?).
But how should I read the JSON string from the JavaScript?
<html> <head> <script src="jquery-1.6.2.min.js"></script> <script src="myscript.js">{"org": 10, "items":["one","two"]}</script> </head> <body> Hello </body> </html>
In this JavaScript I would like to use the JSON argument {"org": 10, "items":["one","two"]}
from the HTML document. I don't know if it's best to do it with jQuery or without.
$(function() { // read JSON alert("the json is:") })
Use the fetch() Function to Load JSON Files in JavaScriptdata . This function is only suitable for working in the web-based environment as the fetch API works only in that environment. After reading the file, we parse the data using json() function and display it.
JSON is a text-based data format following JavaScript object syntax, which was popularized by Douglas Crockford. Even though it closely resembles JavaScript object literal syntax, it can be used independently from JavaScript, and many programming environments feature the ability to read (parse) and generate JSON.
You can use JavaScript like... Just give the proper path of your json file... Simply getting the data and appending it to a div... Initially printing the length in alert. that abc.
JavaScript provides a built-in JSON object for parsing and serializing JSON data. You can use the JSON. stringify() method to convert your JSON object into its string representation, and then use the file system fs module to write it to a file. Be careful when you use synchronous file operations in Node.
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.
I ended up with this JavaScript code to be independent of jQuery.
var jsonElement = document.getElementById('json-script-tag'); var myObject = JSON.parse(jsonElement.textContent);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With