javascriptjqueryjsongetjson

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


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?


Solution

  • 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>