OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Load local JSON file into variable

  • Thread starter Thread starter PogoMips
  • Start date Start date
P

PogoMips

Guest
I'm trying to load a .json file into a variable in javascript, but I can't get it to work. It's probably just a minor error but I can't find it.

Everything works just fine when I use static data like this:

Code:
var json = {
  id: "whatever",
  name: "start",
  children: [{
      "id": "0.9685",
      "name": " contents:queue"
    }, {
      "id": "0.79281",
      "name": " contents:mqq_error"
    }
  }]
}

I put everything that's in the {} in a content.json file and tried to load that into a local JavaScript variable as explained here: load json into variable.

Code:
var json = (function() {
  var json = null;
  $.ajax({
    'async': false,
    'global': false,
    'url': "/content.json",
    'dataType': "json",
    'success': function(data) {
      json = data;
    }
  });
  return json;
})();

I ran it with the Chrome debugger and it always tells me that the value of the variable json is null. The content.json file resides in the same directory as the .js file that calls it.

What did I miss?

<p>I'm trying to load a .json file into a variable in javascript, but I can't get it to work. It's probably just a minor error but I can't find it.</p>

<p>Everything works just fine when I use static data like this:</p>

<pre class="lang-js prettyprint-override"><code>var json = {
id: "whatever",
name: "start",
children: [{
"id": "0.9685",
"name": " contents:queue"
}, {
"id": "0.79281",
"name": " contents:mqq_error"
}
}]
}
</code></pre>

<p>I put everything that's in the <code>{}</code> in a <code>content.json</code> file and tried to load that into a local JavaScript variable as explained here: <a href="https://stackoverflow.com/questions/2177548/load-json-into-variable">load json into variable</a>.</p>

<pre class="lang-js prettyprint-override"><code>var json = (function() {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': "/content.json",
'dataType': "json",
'success': function(data) {
json = data;
}
});
return json;
})();
</code></pre>

<p>I ran it with the Chrome debugger and it always tells me that the value of the variable <code>json</code> is <code>null</code>. The <code>content.json</code> file resides in the same directory as the .js file that calls it.</p>

<p>What did I miss?</p>
 

Latest posts

Top