I am writing some code in JavaScript. In this code i want to read a json file. This file will be loaded from an URL.
How can I get the contains of this JSON file in an object in JavaScript?
This is for example my JSON file located at ../json/main.json
:
{"mainStore":[{vehicle:'1',description:'nothing to say'},{vehicle:'2',description:'nothing to say'},{vehicle:'3',description:'nothing to say'}]}
and i want to use it in my table.js
file like this:
for (var i in mainStore) { document.write('<tr class="columnHeaders">'); document.write('<td >'+ mainStore[i]['vehicle'] + '</td>'); document.write('<td >'+ mainStore[i]['description'] + '</td>'); document.write('</tr>'); }
Approach: Create a JSON file, add data in that JSON file. Using JavaScript fetch the created JSON file using the fetch() method. Display the data on the console or in the window.
Don't get me wrong - jQuery is still a wonderful library and most often than not you will be better off using it. However, for smaller things like simple pages with limited JS interactions, browser extensions and mobile sites, you can use vanilla JS.
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.
Chrome allows you to access local JSON or other data files if you launch it with the --allow-file-access-from-files flag. I checked this with the code above on version 34.0. 1847.131 m; it should work on other versions as well.
Here's an example that doesn't require jQuery:
function loadJSON(path, success, error) { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState === XMLHttpRequest.DONE) { if (xhr.status === 200) { if (success) success(JSON.parse(xhr.responseText)); } else { if (error) error(xhr); } } }; xhr.open("GET", path, true); xhr.send(); }
Call it as:
loadJSON('my-file.json', function(data) { console.log(data); }, function(xhr) { console.error(xhr); } );
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