36


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

Paull
  • 1,020
  • 1
  • 12
  • 21
  • 1
    Depends on the server. I do not see a problem in doing something like var json=<%=jsonString%> – mplungjan Nov 07 '10 at 08:34
  • 1
    Why do you want a synchronous request? – Gumbo Nov 07 '10 at 09:06
  • 3
    I think I want it synchronous because I want to wait my variable to be initialized with json content before using it in following statements (that make no sense without that json data). – Paull Nov 07 '10 at 16:22
  • If I get it correctly json=<%=jsonString%> requires the jsonString to be loaded thru an http request, right? – Paull Nov 07 '10 at 16:42
  • I found this brief tutorial easy to understand: Synch load of JSON in jQuery http://hippieitgeek.blogspot.se/2013/06/load-json-files-synchronously-with.html – MZaragoza Apr 21 '15 at 01:29

7 Answers7

37

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.

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
  • 6
    I think async: false is deprecated since at least jquery v1.11. Here's the message I get in the console: Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/. – Adam Pflantzer Sep 28 '15 at 15:42
  • 1
    Maybe it is deprecated, so what is the alternative? – bgmCoder Oct 26 '17 at 16:59
  • @AdamPflantzer Per [the documentation](https://api.jquery.com/jquery.ajax/), `async` has been deprecated since 1.8. – M. Justin Mar 18 '22 at 04:33
16

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 ;)

Boris Hamanov
  • 3,085
  • 9
  • 35
  • 58
5

if you're using a server script of some sort, you could print the data to a script tag on the page:

<script type="text/javascript">
var settings = <?php echo $json; ?>;
</script>

This will allow you to use your data synchronously rather than trying to use AJAX asynchronously.

Otherwise you'll have to wait for the AJAX callback before continuing on with whatever it is you're doing.

zzzzBov
  • 174,988
  • 54
  • 320
  • 367
2

I only needed to read a small input file provided in json format and extract a small amount of data. This worked just fine in the circumstances:

json file is in the same directory as the script and is called data.json, it looks something like this:

{"outlets":[
        {
            "name":"John Smith",
            "address":"some street, some town",
            "type":"restaurant"
        },
..etc...

read the data into js like this:

var data = <?php echo require_once('data.json'); ?>; 

Access the data items like this:

for (var i in data.outlets) {    
var name = data.outlets[i].name;
... do some other stuff...
}
  • 2
    This is exactly what i'm looking to do. So there isn't a way in which i can include the JSON as a page resource ( ) and then read from it? I have to do a declaration in the included file? That feels like a very dirty way to do it – 2bigpigs Mar 01 '14 at 08:33
0

If RequireJS is an option, you can make it a dependency using requirejs. I use it to mock data in my Angular application. It's essential that some of the mocked data is there before the bootstrap of the app.

//Inside file my/shirt.js:
define({
    color: "black",
    size: "unisize"
});

Just wrap the json data in a define and declare it as a dependency. More info here: http://requirejs.org/docs/api.html#defsimple

smets.kevin
  • 1,570
  • 14
  • 17
-2

AFAIK jQuery has deprecated synchronous XHR requests because of the potential for performance issues. You could try wrapping your app code up in the XHR response handler as in the following:

$(document).ready(function() {
  $.get('/path/to/json/resource', function(response) {
    //'response' now contains your data
    //your app code goes here
    //...
  });
});
james-geldart
  • 709
  • 7
  • 9
-2

The modern HTML5 way without jQuery would be:

   var url="https://api.myjson.com/bins/1hk8lu" || "my.json"
   var ok=await fetch(url)
   var json=await ok.json()
   alert(a.test)