JSON+Javascript/jQuery. How to import data from a json file and parse it?
An example how to do this could be:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$.getJSON('names.json',function(data){
console.log('success');
$.each(data.employees,function(i,emp){
$('ul').append('<li>'+emp.firstName+' '+emp.lastName+'</li>');
});
}).error(function(){
console.log('error');
});
});
</script>
</head>
<body>
<ul></ul>
</body>
</html>
You can simply include a Javascript file in your HTML that declares your JSON object as a variable. Then you can access your JSON data from your global Javascript scope using data.employees
, for example.
index.html:
<html>
<head>
</head>
<body>
<script src="data.js"></script>
</body>
</html>
data.js:
var data = {
"employees": [{
"firstName": "Anna",
"lastName": "Meyers"
}, {
"firstName": "Betty",
"lastName": "Layers"
}, {
"firstName": "Carl",
"lastName": "Louis"
}]
}
Your JSON file does not contain valid JSON. Try the following instead.
{
"employees":
[
{
"firstName": "Anna",
"lastName": "Meyers"
},
{
"firstName": "Betty",
"lastName": "Layers"
},
{
"firstName": "Carl",
"lastName": "Louis"
}
]
}
You should then see a response. Check out http://jsonlint.com/