0

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

1

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

i need to use each as the json file may contains data for more than one person
@h_a86 I see. You may want to update your JSON example then as the structure would have an impact on the proper answer. In general terms your original solution just needs to go one reference deeper (i.e. field.info.email rather than just field.)
2

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.

1 Comment

Without the each call you will need to reference it as result.field.info.email etc., no?
0

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);
          );
        });
    });
});

Comments

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.