2

I have a json array , returned from an api call, as follows:

["meta", {"previous"=>nil, "total_count"=>12, "offset"=>0, "limit"=>1, "next"=>"/v1/Account/MAMTE4MTHJNJRKODBIMD/AvailableNumberGroup/?prefix=415&limit=1&country_iso=US®ion=NY&offset=1"}]["api_id", "441d610c-bede-11e2-815d-22000abcc0e1"]["objects", [{"stock"=>57, "voice_enabled"=>true, "region"=>"New York, UNITED STATES", "voice_rate"=>"0.00900", "prefix"=>"631", "sms_rate"=>"0.00800", "number_type"=>"local", "setup_rate"=>"0.00000", "rental_rate"=>"0.80000", "group_id"=>"11411650673450", "sms_enabled"=>true, "resource_uri"=>"/v1/Account/MAMTE4MTHODBIMD/AvailableNumberGroup/11411650673450/"}]]

I can print the whole array with this

success: function(response){
             $.each([response], function(i, objects) {
             var list = "<li>" + objects + "</li>";
             $('#result').append(list);
             });

How can I extract specified items and print them within the <li> .. </li> to make a list of some but not all of the elements?

Many thanks!

1
  • is this JSON at all or are you withholding any info ? Commented May 17, 2013 at 12:29

4 Answers 4

2

You can do that by accessing " i ". This will have your properties of all JSON object.

success: function(response){
             $.each([response], function(i, objects) {
             var list = "<li>" + **i.previous** + "</li>";

             $('#result').append(list);
             });

ANother example

var obj = {
  "flammable": "inflammable",
  "duh": "no duh"
};
$.each( obj, function( key, value ) {
  alert( key + ": " + value );
});

Out put being:

flammable: inflammable 
duh: no duh
Sign up to request clarification or add additional context in comments.

1 Comment

thank you, what exactly should i.previous be? i.voice_rate for example? If you mean i.voice_rate (which is one of the objects), I am afraid it does not work.
1
var arr = ["meta", {"previous"=>nil, "total_count"=>12, "offset"=>0, "limit"=>1, "next"=>"/v1/Account/MAMTE4MTHJNJRKODBIMD/AvailableNumberGroup/?prefix=415&limit=1&country_iso=US®ion=NY&offset=1"}]["api_id", "441d610c-bede-11e2-815d-22000abcc0e1"]["objects", [{"stock"=>57, "voice_enabled"=>true, "region"=>"New York, UNITED STATES", "voice_rate"=>"0.00900", "prefix"=>"631", "sms_rate"=>"0.00800", "number_type"=>"local", "setup_rate"=>"0.00000", "rental_rate"=>"0.80000", "group_id"=>"11411650673450", "sms_enabled"=>true, "resource_uri"=>"/v1/Account/MAMTE4MTHODBIMD/AvailableNumberGroup/11411650673450/"}]];

    for(var i=0;i<arr.length;i++){
        var obj = arr[i];
        for(var key in obj){
            var attrName = key;
            var attrValue = obj[key];
            //your condition goes here then append it if satisfied
            var list = "<li>" + obj[key]+ "</li>";
            $('#result').append(list);
        }
    }

Thanks.

2 Comments

thank you, this partially works ... in that it makes a long vertical list of each letter (not object) of the object. I need to generate a list like this: <li> voice rate: obj_voice_rate </li>
this is what it looks like: plivo.com/docs/api/numbers/availablenumbergroup and I need to access the objects section.
1

You need a double iteration, one for each object in objects[] and one for each <key, value> pair in an object.

For example in this demo, using an example from http://plivo.com/docs/api/numbers/availablenumbergroup/

var jsonResponse = '{"meta": {"previous": null, "total_count": 1, "offset": 0, "limit": 20, "next": null }, "api_id": "26590c12-5831-11e1-86da-6ff39efcb949", "objects": [{"voice_enabled": true, "voice_rate": "1.1"}, {"voice_enabled": false, "voice_rate": "1.2"} ] }';

$('#simulateAjax').on('click', function() {
    // cannot make call due to cross-domain security (and the API URL is unknown!) so just fake call the success function with valid JSON
/*    $.ajax({
      url: 'test.html',
      dataType: 'json'
    }).done(success);
*/
    success($.parseJSON(jsonResponse));

    function success(response) {
        var items = '';
        $.each(response.objects, function(index, obj) {
            // obj here is one "object", we need to iterate the contents of each "obj"

            $.each(obj, function(k, v) {
                // k here is the key
                // v is the value
                items += '<li>' + k + ' : ' + v + '</li>';
            });
        });
        $('#result').append(items);
    }
    return false;
});

which will produce

  • voice_enabled : true
  • voice_rate : 1.1
  • voice_enabled : false
  • voice_rate : 1.2

Note: I removed most of the properties in each object for the demo. Also jQuery would have automatically called $.parseJson() on the response, which is why I am manually calling it.

If you want each object to appear on a single <li> then you will need to construct the <li> in the outer loop and append the k, and v in the inner $.each(), then close the </li> after, like this:

var item = '<li>';

$.each(obj, function(k, v) {
    item += k + ' : ' + v + ', ';
});

item += '</li>';
items += item;

2 Comments

thanks, that looks great I will see if I can get my head round it. But, I envisage that there may be problems (as have been part of this discussion already, regarding valid json. Is there something wrong with my jquery script above that gets back "non valid" json data? Either way, thank you for the thought you have (all) put into this. You can imagine it has been driving me potty.
If you make a call to https://api.plivo.com/v1/Account/{auth_id}/AvailableNumberGroup/ with your auth_id (don't paste it on SO!) in a browser and there are => present then it is invalid JSON but I can't imagine a resource available to the public will generate invalid JSON. They "JSON" in your question looks like a PHP array.
-1

First of all, that's not valid JSON, since the arrow syntax => is not allowed and you should add double quotes to the values as well. Moreover the syntax doesn't seem to be very consistent, looks like you have more than one array there at the root level. For it to be JSON you need the "key": "value" format, and the "meta" doesn't have a value.

If you can, you need to change it to something like:

{ "meta" : { "previous" : "nil", "total_count" : "12" (...) } }

of if you need multiple sets of data inside the "meta":

{ "meta" : [ { "previous" : "nil", "total_count" : "12" (...) }, (...) ] }

after that you could then do (first option):

function(json) {
  var key, $result = $('#result');
  for (key in json.meta) {
    $result.append("<li>" + json.meta[key] + "</li>")
  }
}

or (second option):

function(json) {
  var item, key, $result = $('#result');
  for (item in json.meta) {
    for (key in json.meta[item]) {
      $result.append("<li>" + json.meta[item][key] + "</li>")
    }
  }
}

3 Comments

thank you, I am unable (or unsure how) to change it so your approach does not work.
Well if you don't have valid JSON like I told you, no approach will work, unless you're not actually using JSON or you're not disclosing some information.
thanks, I am not withholding information. The data I am getting is what is returned and I am not sure how to get "proper" JSON. When, for example in the jquery script, I put $.each(response, etc.. I get no return, when I put $.each([response] (wiht []) I get the non JSN that you have noticed becasue it becomes an array. So what to do? It should be like you can find on this page: plivo.com/docs/api/response (about 3/4 way down). I am nto sure what is going wrong. Do I need to specify dataType in my original jquery above, for example? Thank you for your patience, please don't give up!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.