I'm developing a simple JavaScript (jQuery) slide show. I wanted to use JSON to store some some static parameters about the content of each slide.
Since I like to keep my data separate from my code, is there anyway to have JavaScript evaluate a .json file?
- AJAX seems a bit overkill - it just needs to evaluate it at run-time, nothing is dynamic.
- I could have a separate .js file that holds my JSON data as an object - but this seems messy.
So before I use one of the above solutions, I just wanted to make sure there wasn't a cleaner way to have JavaScript evaluate a text file.
I'm developing a simple JavaScript (jQuery) slide show. I wanted to use JSON to store some some static parameters about the content of each slide.
Since I like to keep my data separate from my code, is there anyway to have JavaScript evaluate a .json file?
- AJAX seems a bit overkill - it just needs to evaluate it at run-time, nothing is dynamic.
- I could have a separate .js file that holds my JSON data as an object - but this seems messy.
So before I use one of the above solutions, I just wanted to make sure there wasn't a cleaner way to have JavaScript evaluate a text file.
Share Improve this question asked Nov 30, 2009 at 20:12 KeyboardInterruptKeyboardInterrupt 3,7638 gold badges37 silver badges41 bronze badges3 Answers
Reset to default 9What's wrong with having a separate js file for your object? It has to live somewhere. I agree ajax is overkill, but I'm at a loss for why you think a JavaScript object in a .js file is "messy."
Evaluating JSON is very easy:
var jsonString = "{'name': 'Joe', 'age': 36}";
var data = eval('(' + jsonString + ')');
data.name // 'Joe'
data.age // 36
The easiest way to store this data is to put it in an <input type="hidden">
and then read it using document.getElementById('hiddenElementId').value
.
The complete picture:
HTML
<input type="hidden" id="hiddenElementId" value="{'name': 'Joe', 'age': 36}" />
JS
function getData() {
var jsonString = document.getElementById('hiddenElementId').value;
var data = var data = eval('(' + jsonString + ')');
return data;
}
It's not actually necessary to be a hidden
element - you can put it in an attribute in one of the images.
Another option is to stick it into a <script>
tag under some name.
<script type="text/javascript">
var data = {'name': 'Joe', 'age': 36};
</script>
This way data
becomes a global variable (something I don't like so much) and can be used from everywhere. It's a simple solution, but a bit messy - I would go with the first one.
J-Query has a parse JSON function that even works in IE..
$.parseJSON("{'json':'rules for data'}");
Enjoy..
but just a question how to make it tidy like:
FUNCTION_HOWTO({json:'test',p2:'part2'}) = {
json:'test',
p2:'part two'
}