Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I open a JSON file in JavaScript without jQuery?

Tags:

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>'); }  
like image 926
Rick Weller Avatar asked Mar 23 '12 11:03

Rick Weller


People also ask

How do I open a JSON file in JavaScript?

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.

Can we use JavaScript without jQuery?

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.

Can you use JSON in JavaScript?

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.

How do I open a JSON file locally?

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.


1 Answers

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); } ); 
like image 82
Drew Noakes Avatar answered Sep 30 '22 14:09

Drew Noakes