Seb Thomas
Seb Thomas

Reputation: 107

Loop through json array string

Using the following code, I am getting the json array string in the div (named remoteFeed)
Say it shows:

{"id":"25","name":"Basil","country":"USA"}

My question is how can I get the json array elements?

Pl note that even though it shows the value in the div -- the alert (see below) shows blank!!!

alert(data);  //-------------------Shows blank

NB: Being a newbie I was trying to get the value first. But in this case we have to convert it to json object. So if you know a better way, so that I get the values (id, name..) on the client side that is more advisable

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="http://code.jquery.com/jquery-latest.js"></script>

<script type="text/javascript">


(function ($) {
$(document).ready(function(){
  $('#remoteFeed').load('http://testservice/json/');

  var data = remoteFeed.innerHTML;
  alert(data);  //-------------------Shows blank

  /*
              var jsonObj = JSON.stringify(eval("(" + data + ")"));
              for(var i in jsonObj)
            {
            var id = data[i].country_code;
            alert(id);
            }

  */
});
})(jQuery);


 var data = remoteFeed.innerHTML;
  alert(data);

</script>

</head>
<body>

      <div id="remoteFeed"></div>

</body>

Upvotes: 0

Views: 285

Answers (2)

Boaz
Boaz

Reputation: 20230

Why the alert() is blank

You're getting a blank value in the alert() call because you're not waiting for the load() request to complete. Instead of immediately alerting the value, consider passing a callback function to load(). The callback function is executed once the request is completed.

For example:

$('#remoteFeed').load('http://testservice/json/', function() {
    alert($('#remoteFeed').html());
});

How to treat a JSON string as an object

Basically, you can use the native JSON object in modern browsers to parse a JSON string into an object.

For example:

var json_object = JSON.parse(json_string);

Alternatively, you'll be far better off using one of jQuery's other AJAX functions, that are more suitable to this task than load() which is meant for loading HTML.

For example:

$.getJSON('http://testservice/json/', function(json_object) {
    for(var i in json_object) {
       var id = json_object[i].country_code;
       alert(id);
    }
});

In this example the method $.getJSON() performs an AJAX request, assumes the returned data is in JSON format and automatically parses it for you. The callback function is then passed the resulting JSON object.

Upvotes: 1

To get json result data you can use jQuery.getJSON() method

refer the jquery site http://api.jquery.com/jquery.getjson/

Upvotes: 0

Related Questions