Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include JSON data in javascript synchronously without parsing?


I want to load a JSON file from my own server containing an array into a javascript Object variable.
I would like to do it at the beginning of page load in a synchronous way because data is needed during page load.

I managed to use jQuery.getJSON but this is asynch ajax and it seems a little overkill.

Is there a way to load JSON in a synch way without doing your own parsing?
(more or less like using a <script language="JavaScript" src="MyArray.json"></script>)

Thanks in advance for any help, hope it makes sense since I am a javascript newbie. Paolo

like image 213
Paull Avatar asked Nov 07 '10 08:11

Paull


People also ask

Is JSON parse synchronous?

The json parse() is a built-in JavaScript function that converts text into objects. The json. parse() function is converting json string to object. The parse() method is synchronous, so the more the JSON data is big, the more time your program execution will be blocked until the JSON is finished parsing.

Can JavaScript parse JSON natively?

JSON is a JavaScript-based object/value encoding format that looks very close to raw JavaScript and can be very easily parsed by JavaScript code because JavaScript can effectively evaluate a JSON string and re-materialize an object from it.


2 Answers

getJSON() is simply shorthand for the ajax() function with the dataType:'json' set. The ajax() function will let you customize a lot about the request.

$.ajax({   url: 'MyArray.json',   async: false,   dataType: 'json',   success: function (response) {     // do stuff with response.   } }); 

You still use a callback with async:false but it fires before it execution continues on from the ajax call.

like image 196
Alex Wayne Avatar answered Oct 11 '22 00:10

Alex Wayne


Here you go:

// Load JSON text from server hosted file and return JSON parsed object function loadJSON(filePath) {   // Load json file;   var json = loadTextFileAjaxSync(filePath, "application/json");   // Parse json   return JSON.parse(json); }     // Load text with Ajax synchronously: takes path to file and optional MIME type function loadTextFileAjaxSync(filePath, mimeType) {   var xmlhttp=new XMLHttpRequest();   xmlhttp.open("GET",filePath,false);   if (mimeType != null) {     if (xmlhttp.overrideMimeType) {       xmlhttp.overrideMimeType(mimeType);     }   }   xmlhttp.send();   if (xmlhttp.status==200 && xmlhttp.readyState == 4 )   {     return xmlhttp.responseText;   }   else {     // TODO Throw exception     return null;   } } 

NOTE: This code works in modern browsers only - IE8, FF, Chrome, Opera, Safari. For obosolete IE versions you must use ActiveX, let me know if you want that I will tell you how ;)

like image 26
Boris Hamanov Avatar answered Oct 10 '22 23:10

Boris Hamanov