h_h
h_h

Reputation: 1231

Retrieving values from JSON with jQuery

I have been using this JSON

{ 
    "firstName": "John",
    "lastName": "Doe",
    "age": 25,
    "info": { 
        "email": "[email protected]",
        "url": "http://"
    }
}

With this jQuery function

<script>
    $(document).ready(function() {
        $("button").click(function() {
            $.getJSON("demo_ajax_json.js", function(result) {
                $.each(result, function(i, field) {
                    $("div").append(field + " ");
                });
            });
        });
    });
</script>

I want to extract the values of email and url from above given JSON. Can anybody help me in this regard.

Thank you

Upvotes: 0

Views: 873

Answers (3)

Ram Singh
Ram Singh

Reputation: 6938

try the following code:

<script>
$(document).ready(function() {
    $("button").click(function() {
        $.getJSON("demo_ajax_json.js", function(data) {
            var Append = "";
              for (var i = 0; i < data.d.length; i++) {
              Append +=title="' + data.d[i].FriendName + '";
              }
            $("div").append(Append);
          );
        });
    });
});

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337700

Replace this:

$.each(result, function(i, field) {
    $("div").append(field + " ");
});

With this:

$("div").append(result.field.info.email);
$("div").append(result.field.info.url);

You don't need the each as you're only returning one set of data and are trying to access it's properties directly.

Upvotes: 2

Tom Hubbard
Tom Hubbard

Reputation: 16139

No need to do it in an each call.

<script>
    $(document).ready(function() {
        $("button").click(function() {
            $.getJSON("demo_ajax_json.js", function(result) {
                $("div").append(result.info.email + " " + result.info.url);
              );
            });
        });
    });
</script>

Note that by selecting "div" you will be appending the info into ALL divs on the page.

Upvotes: 3

Related Questions