user1760110
user1760110

Reputation: 2336

How to parse JSON object with $.ajax() method

I am trying to parse a JSON object (not stored on a file) by using $.ajax() method but it is not functioning. What am I doing wrong?

var painting = [
        {
        "title": "Boardwalk 5",
        "artist": "Arnie Palmer",
        "image": "ap1.jpg",
        "price": 850
        },
        {
        "title": "A Lasting Piece",
        "artist": "Arnie Palmer",
        "image": "ap2.jpg",
        "price": 450
        },
        {
        "title": "Surf at High Tide",
        "artist": "Arnie Palmer",
        "image": "ap3.jpg",
        "price": 950
        },
        {
        "title": "The Games We Play",
        "artist": "Arnie Palmer",
        "image": "ap4.jpg",
        "price": 850
        }
      ];
$(document).ready(function () {
$.ajax({
    type: 'GET',
    url: 'painting',
    dataType: 'json',
    success: jsonParser
});

});

function jsonParser(json) {
    $.getJSON(painting, function(data){
        $.each(painting, function(k,v){
            var title = v.title;
            var price = v.price;
            $('#container').append('<div class="painting"><br/><div class="title">' + title + '<br/>$' + price + '</div></div>')
        });
    });
}

Upvotes: 0

Views: 121

Answers (2)

Su4p
Su4p

Reputation: 865

Maybe he's trying to get a json from a file ?

Maybe painting.json or painting is his json file. that'll explain why he's using ajax and getJson.

You have to understand that $.getJSON uses $.ajax.

So :

var painting = [
    {
    "title": "Boardwalk 5",
    "artist": "Arnie Palmer",
    "image": "ap1.jpg",
    "price": 850
    },
    {
    "title": "A Lasting Piece",
    "artist": "Arnie Palmer",
    "image": "ap2.jpg",
    "price": 450
    },
    {
    "title": "Surf at High Tide",
    "artist": "Arnie Palmer",
    "image": "ap3.jpg",
    "price": 950
    },
    {
    "title": "The Games We Play",
    "artist": "Arnie Palmer",
    "image": "ap4.jpg",
    "price": 850
    }
  ];
  $(document).ready(function () {

    $.getJSON('painting.json', function(data){
        $.each(data, function(k,v){
            var title = v.title;
            var price = v.price;
            $('#container').append('<div class="painting"><br/><div class="title">' + title  + '<br/>$' + price + '</div></div>')
        });

     });
});

is enough

Upvotes: 0

dkasipovic
dkasipovic

Reputation: 6120

Why do you need .ajax to parse json that is in variable?

Have you tried only this:

$.each(painting, function(k,v){
  var title = v.title;
  var price = v.price;
  $('#container').append('<div class="painting"><br/><div class="title">' + title + '<br/>$' + price + '</div></div>')
});

If I understood you good, you do not need .getjson and .ajax since those are Ajax calls to retrieve external data?

Upvotes: 2

Related Questions