How to use JSON as a configuration file with Javascript

I am looking for a way that I can use JSON as a configuration file,

My JSON configuration file looks like this:

{ 'Lang' : 'EN', 'URL' : '/over/dose/app' } 

and I want to get the URL and Lang in the html file using javascript or jQuery. I do not want to use an asynchronous method, for example $.getJson .

I want to get Url and language from a JSON file something like this:

 var url = myjson.URL; 

so I can use var later in many different functions.

+8
json javascript jquery
source share
2 answers

If you do not want to use an asynchronous call, you can always assign a variable to the config object and put the file in the src script tag

 var appConfig={ 'Lang' : 'EN', 'URL' : '/over/dose/app' } 

,

 <script src="/path/to/config.js"></script> <script> alert(appConfig.URL);</script> 

The advantage is immediate download. A possible flaw is that it is no longer a json file, it is a regular javascript file in case you write to it from the server code.

Of course, this also creates a global variable.

+15
source share

something like

 var cfg = {}; $.ajax({ url: myUrl, async: false, success: function(data) { cfg = JSON.parse(data); } }); 
+1
source share

All Articles