views:

853

answers:

3

I'm looking for the "best practice" as to where the JSON should be stored if it's just a string array. Should it be stored in a variable in a script block in the HTML page? Should it be stored in a JavaScript file outside of the HTML for separation? Or should it be stored in the plugin itself?

If it should be an external js file, what's the "best practice" naming scheme for the file? I know the accepted jQuery plugin name is jquery.plugin.js or jquery.plugin-min.js (for the minified file).

+5  A: 

Depends, if you need the JSON right away you can store it anywhere to get it executed:

<script> var myJsonObj = { ... }; </script>

If it's a lot of Data and you don't need the data right away, you can always make an ajax call to a file named something like "data.json".

For naming the plugin name, well it's really up to you, but yeah I believe jquery.pluginname.js is the standard way of doing it.

Luca Matteis
So if I named it data.json, I'm assuming I'd just use getJSON to obtain the file?
Jason N. Gaylord
$.getJSON uses the "script" tag hack to get the data, which you should only use for "cross-domain" requests, in my opinion. A simple $.ajax is enough.
Luca Matteis
A: 

I'll second sktrdie to add the extension .json for a file like this. A gotcha that I ran across when first playing with JSON is that a JSON string is not a valid JavaScript File.

For example, If I call a file with this content:

{
    'foos': 'whatever',
    'bar': false,
    'items': [1,2,3]
}

as the src of a <script> tag, I get this error:

Error: invalid label
Line: 2, Column: 1
Source Code:
 'foos': 'whatever',

In the past I've actually hidden JSON strings in <divs> or spans like this:

<div id="jsonStorage" style="display:none">
{'foos': 'whatever','bar': false,'items': [1,2,3]}
</div>

I've also used hidden form fields for this.

artlung
How would you reference a string constant within JS? You have to assign 'var a = {'foos': 'whatever'}' and include the JS.
kRON
A: 

If it's part of the plugin, i.e. default config, I'd store it in the plugin file itself. If it's an external config for the plugin, then it depends. It might make sense to store it in a variable in the HTML, i.e.

<script>
var myConfig = {
  "foo" : "bar"
};
</script>

This could especially be the case if you need any of the JSON to be generated by your back-end code.

Really, the answer is "it depends" -- can you give more details?

rmurphey