0

I suspect my problem is due to the structure of my JSON string. It seem to have a JSON object within a JSON object.

This is the format of my JSON:

[
{"subject":{"title":"java","id":"1","desc":"Basic java programming"}, 
{"subject":{"title":"objective c","id":"2","desc":"Introduction to objective c"}
}

This is my jquery code:

var items = [];

    $.getJSON('theurl', function(data) {

        $.each(data, function(key, subject) {
            alert(subject); //returning me "[object Object]"
            $('#tempresult').append('<p>'+ subject +'</p>'); //returning me "[object Object]"
        });
    });
1
  • That looks correct based on your object. What do you want instead? Commented Sep 30, 2011 at 3:32

3 Answers 3

3

You have posted some malformed JSON. I'm going on the assumption that your elements are closed properly as:

[
  {"subject":{"title":"java","id":"1","desc":"Basic java programming"}},
  {"subject":{"title":"objective c","id":"2","desc":"Introduction to objective c"}}
]

It looks like you want $('#tempresult').append('<p>'+ subject.subject.desc +'</p>');

data[0] is this object:

{"subject":{"title":"java","id":"1","desc":"Basic java programming"}}

data[1] is this object:

{"subject":{"title":"objective c","id":"2","desc":"Introduction to objective c"}}

data[0].subject is this object:

{"title":"java","id":"1","desc":"Basic java programming"}

data[0].subject.desc is this:

"Basic java programming"
Sign up to request clarification or add additional context in comments.

Comments

1

Your example JSON is a bit poorly formed (missing a }).

Otherwise, try this:

$.each(data, function(key, subject) {
    alert(subject.subject.title);
});

http://jsfiddle.net/7xMJP/

Comments

1

Your subject variable is a json object. You have to specify the subject properties to get the value

alert(subject.subject.id); alert(subject.subject.title); Alert(subject.subject.desc);

2 Comments

i made the same mistake at first, but given his malformed JSON, i assume that the title, id, desc objects are wrapped in an obj with a key of subject: you'll need subject.subject[...name...] instead of just subject[...name...]
That's true, silly me. I'm on a mobile and i have limited screen. Thank you zzzzBov for noticing me.

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.