Tuesday, 18 April 2017

Javascript read JSON file and loop through records(optional with JQuery)

Hi all, here a very fast example on how to read json data from file in Javascript,
here the content of *.htm file:


<!DOCTYPE html>
<html>
<head>
    <title>LWebCode Javascript Read JSON from file</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
    <script type="text/javascript" src="mydata.json"></script>
    <script>
        function ReadData()
        {
            var dataLstAz = JSON.parse(jsLstData);
            alert(jsLstData.length);
          
            for (var key=0, size=jsLstData.length; key<size; key++)
            {
                var obj = jsLstData[key];
                liout = obj.Name + ", " + obj.Age + "<br/>";
                $("#Output").append(liout);
            }
        }
      
        $( document ).ready(function() {
            ReadData();
        });
    </script>
</head>
<body>
    <div id="Output">
    </div>
</body>
</html>


Here the content of "mydata.json" file,
put this file in same folder of *.htm file, or change path in *.htm file:


jsLstData = '[{"Name":"MyName1","Age":"20"}, {"Name":"MyName2","Age":"22"}]';
//End of file "mydata.json"


Now simply open *.htm file in browser and you'll get this output:

MyName1 20
MyName2 22


That's it, hope it helps

No comments:

Post a Comment