0

The JSON looks like this:

   [  {"animal":"dog", "sound": "bark"}, 
      {"animal":"cat", "sound": "meow"} ]

and I want to iterate each record {...} inside the brackets [ ], first the dog-record and then the cat-record. If it is possible to reference each record in turn using $.each(), how is that done?

2 Answers 2

1

I am assuming we are starting from a JSON string, rather than an actual javascript array notation (it was unclear to me from the question as to what you are starting with). Here is some sample usage:

var json = '[{"animal":"dog", "sound": "bark"},{"animal":"cat", "sound": "meow"}]';
var jsonObjectArray = $.parseJSON(json);
$.each(jsonObjectArray, function(i, obj) {
    // do something
    console.log(obj.animal);
    console.log(obj.sound);
});
Sign up to request clarification or add additional context in comments.

4 Comments

Why parse the JSON? He's running it in <script>
He said he had JSON. JSON is a string format. It must be parsed to turn it into a usable array of objects. Now, if in reality he already has a javascript array with object literals in it, he could simply skip the two first lines and go directly to the third.
He never really specified whether he had it as an object or string.But I'll agree with you, best parse it just to be sure.
@bobthyasian You don't parse it just to make sure. If you try to parse a non-string that will not work. You need to know exactly what you are working with and take the appropriate steps needed to get the data in the format you need.
1

With an array in JSON format, you can directly access the variable names.

If you are creating this JSON from a String, then @Mike is right, you must parse the JSON first. I was under the assumption that you had JSON returned from a server POST.

var animals_json = '[{"animal":"dog", "sound": "bark"}, {"animal":"cat", "sound": "meow"}]';
var animals_parsed = $.parseJSON(animals_json);
$.each(animals_parsed, function (i, elem) {
    console.log(elem.animal + " makes a " + elem.sound);
});

If your JSON is returned from a server side, from say, a PHP page, then you can use it without parsing:

// SERVER SIDE
<?php
   //... create JSON
   $animals = array(
            array('animal' => 'dog', 'sound' => 'bark'), 
            array('animal' => 'cat', 'sound' => 'meow')
    );
?>

// CLIENT SIDE
<html>
<script>
    // RETURN FROM PHP PAGE ECHO VIA AJAX PERHAPS //
    var animals = <?php echo json_encode($animals) ?>;

    $.each(animals, function (i, elem) {
        console.log(elem.animal + " makes a " + elem.sound);
    });
</script>
</html>

7 Comments

Would need to parse the JSON first in this instance.
Have updated my post to clarify. I assumed he had JSON returned from a json_encode() call server side, as he said "The JSON looks like this:" ... But you're right, my array in the example is created in JS. Thanks!
@MikeBrant Could you remove the downvote if my answer looks good now?
Even if json is received from a server call via AJAX, it is still a string, which means you need to parse it into a usable array or object. The only reason I am kind of a stickler about this is that this is a large source of confusion for newer developers and you see any number of questions/answer on Stack Overflow using the term incorrectly. Of course with libraries like jQUery, sometimes this string to object/array conversion goes on under the hood, but even then it is important for developer to know the jQuery is actually making the string to object/array conversion for them.
@MikeBrant Id love to learn about this if I'm misunderstanding, but my PHP example above works perfect for me. On page load, I return an array with json_encode($array) from my PHP function, and then I immediately use $.each to iterate it. Where is the String-> object conversion happening that you speak of? I have updated my code above to reflect this situation.
|

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.