jQuery & Javascript – Read JSON files on server

Here is an simple project which demonstrate how to read a JSON file in jQuery and Javascript.

Project structure

- (webroot folder)
  - data
    - file-1.json
    - file-2.json
  - js
    - script.js
  - index.html

 

data/file-1.json

[
  {
    "name"  : "Apple",
    "color" : "red",
    "origin": "U.S."
  },
  {
    "name"  : "Orange",
    "color" : "orange",
    "origin": "U.K."
  },
  {
    "name"  : "Strawberry",
    "color" : "red",
    "origin": "Japan"
  }
]

 

data/file-2.json

[
  {
    "name"  : "Banana",
    "color" : "yellow",
    "origin": "Singapore"
  },
  {
    "name"  : "Pineapple",
    "color" : "greenish yellow",
    "origin": "Malaysia"
  },
  {
    "name"  : "Watermelon",
    "color" : "green",
    "origin": "Taiwan"
  }
]

 

index.html

<!doctype html>
<html>
<head>
  <title>Read JSON</title>
</head>
<body>
  <select id="data">
    <option value="./data/file-1.json">file-1.json</option>
    <option value="./data/file-2.json">file-2.json</option>
  </select> 
  
  <button id="btn">Read</button>
  
  <div id="result"></div>

   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
   <script src="./js/script.js" type="text/javascript"></script>
</body>
</html>

 

js/script.js

$("#btn").click(function(){

  var file = $("#data").val();

  $.getJSON(file, function(json) {
    // console.log(json);
    $("#result").html('');

    for (var i = 0; i < json.length; i++) {

      $("#result").append('<p>name  : ' + json[i].name   + '</p>');
      $("#result").append('<p>color : ' + json[i].color  + '</p>');
      $("#result").append('<p>origin: ' + json[i].origin + '</p>');
      $("#result").append('<hr>');
    }
  });

});

6. If you are running the index.html locally, you will probably come across the Access-Control-Allow-Origin issue. Please refer to the following post to resolve it.

 

7. Check it out!
read-json-in-jquery-and-javascript
 

Done =)

Advertisements

One thought on “jQuery & Javascript – Read JSON files on server”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s