0

I am getting json response like this

{"item_id":"1","item_title":"Item 1"}{"item_id":"2","item_title":"Item 2"}

how would I parse this for each data returned?

Tried

$.ajax({
                          url: 'linktojson',
                          type: "post",
                          dataType: "json",
                          success: function (response) {
                              //console.log('isok');
                              if (response.item_id) {
                                 $('#posts').html(response.item_id);
                              }
                          }
                        });

but works only if I have 1 item in the response.

thank you!

1
  • response can't be a series of objects, needs to only one object. Run your response through jsonlint.com to check validation Commented Jun 23, 2012 at 18:15

3 Answers 3

3

After you return valid JSON from server then You can traverse the json object using $.each like

success: function (response) {
    $.each(response,function(i,item){
        $('#posts').append(item.item_id+"<br />"); 
    });
}

Demo: http://jsfiddle.net/joycse06/DxaaV/

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

Comments

1

That isn't valid JSON, it works with one element only.

Read JSON

OR use json_encode on PHP side (assuming you are using PHP)

2 Comments

it is json_encode but foreach , I see what you are saying. let me try
if you have many arrays, merge all of them into a single one and then use json_encode
1

You should get an array of objects like this:

var variable = [{"item_id":"1","item_title":"Item 1"}, {"item_id":"2","item_title":"Item 2"}];

So modify the response to be like above. Here is the fiddle: http://jsfiddle.net/YZ6Fc/

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.