JSON+Javascript/jQuery. How to import data from a json file and parse it?

GarouDan picture GarouDan · May 8, 2012 · Viewed 62.2k times · Source

If I have a JSON file named names.json with:

{"employees":[
    {"firstName":"Anna","lastName":"Meyers"},
    {"firstName":"Betty","lastName":"Layers"},
    {"firstName":"Carl","lastName":"Louis"},
]}

How can I use its content in javascript?

Answer

kbec picture kbec · May 8, 2012

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>