views:

176

answers:

8

I have this kind of json string:

{"total":"3","data":[{"id":"4242","title":"Yeah Lets Go!","created":"1274700584","created_formated":"2010-07-24 13:19:24","path":"http:\/\/domain.com\/yeah"}{"id":"4242","title":"Yeah Lets Go!222","created":"1274700584","created_formated":"2010-07-24 13:19:24","path":"http:\/\/domain.com\/yeah222"}{"id":"4242","title":"Yeah Lets Go!333","created":"1274700584","created_formated":"2010-07-24 13:19:24","path":"http:\/\/domain.com\/yeah333"}]}

I would need to parse it to javascript object i believe? And then into html like:

<a href="http:www..domain.com/yeah">Yeah Lets Go!</a>
<p class="date">Created: 2010-07-24 13:19:24"</p>

but I have no clue how to parse it and so on.

I get that string from this:

$('a.link').click(function() {
var item_id = $(this).attr("href").split('#')[1];
$.get(base_url+'/ajax/get_itema/'+item_id+'/0/3/true', null, function(data, status, xhr) {
$('#contentCell').html(data);
});
+3  A: 

Use the JSON.parse function to convert a JSON string into a JS object. Most modern browsers include JSON.parse, but it is also included in json2.js if you need a fallback for older browsers.

CD Sanchez
A: 

Read here about serializing and de-serializing http://www.json.org/js.html

+2  A: 

Since you're using jQuery, take a look at .getJSON()

The way you use .getJSON() is:

jQuery.getJSON( url, [ data ], [ callback(data, textStatus) ] )

url is of course the url you're getting the data from. [ data ] is the stuff you send to the server. [ callback(data, textStatus) ] is a function that handles the data coming back from the server. You can generally leave out the second argument textStatus. The data coming back is understood to be JSON. .getJSON() is shorthand for a .ajax() call that specifies JSON data.

So in your case this would be something like (note that I changed the JSON coming back from the server to response... it's a less confusing nomenclature in your case than using data, since you have a data property in your JSON):

$.getJSON(base_url+'/ajax/get_itema/'+item_id+'/0/3/true', function(response) {
    ...
});

So, to recover things from response we simply access them using dot and square bracket notation. To get the first set of data:

response.data[0].title \\ <== "Yeah Lets Go!"
response.data[0].path \\ <== "http://domain.com/yeah"

The above looks in response which is our JSON object. Then it looks at the first data elment (there are 3) and pick the title in the first line and the path in the second.

Since you're using jQuery you can use .each() to iterate over your 3 data. Like this:

$.each(response.data, function(index, value) {
    $("body").append('<a href="' + value.path + '">' + value.title + '</a>');
    $("body").append('<p class="date">Created: ' + value.created_formated + 
      '</p><br />');
});

jsFiddle example

.each() sanely loops over a collection of items. The first argument of .each(), is the object you want to loop over. This is response.data not merely response. This is because we want to look at response.data[0], response.data[1], and response.data[2]. The second argument of .each() is the callback function, or what we want to do with each of the items we are iterating over. Within the callback function, the first argument is automatically the index of the item (0, 1, or 2 in your case). The second argument is the value of the item. In your case this is a separate object: response.data[0], response.data[1], and response.data[2] respectively. We can use dot notation to retrieve the things we want directly from these objects. In the above example we access .path. .title and .created_formated from each of the values.

This make your entire function:

$.getJSON(base_url+'/ajax/get_itema/'+item_id+'/0/3/true', function(response) {
    $.each(response.data, function(index, value) {
        $("body").append('<a href="' + value.path + '">' + value.title + '</a>');
        $("body").append('<p class="date">Created: ' + value.created_formated + 
          '</p><br />');
    });                
});

Of course you probably want to append the response to (a) specific element/s.

Here's some good info on using .getJSON() to access multidimensional JSON data from another SO question.

Here's some general info about JSON in Javascript.


Note:

You need commas between your curly braces!

You have:

...p:\/\/domain.com\/yeah"}{"id":"4242","title"...

You need:

...p:\/\/domain.com\/yeah"}, {"id":"4242","title"...
Peter Ajtai
+2  A: 

Having a div with id result to get the html, something like:

$.getJSON(base_url+'/ajax/get_itema/'+item_id+'/0/3/true', function(data) {
    $("#result").empty();
    $.each(data.data, function(i, d) {
        $("#result").append("<a href='" + d.path + "'>" + d.title + "</a>" + 
            "<p class='date'>Created: " + d.created_formated + "</p>");
    }
});
RC
A: 

Try a templating engine that convert the JSON to HTML on the browser.

You can have a look at pure.js, it is very fast, and keep the HTML totally clean of any Javascript templating logic. We use it to generate all the HTML from JSON data in our web app.(Yep... I'm a main contributor to the lib)

If you are more familiar with the <%...%> or ${...} kind of templates, there are plenty of them and for any taste if you search on the web for javascript template.

Mic
+1  A: 

I don't found in any answers that the data which you posted are NOT valid JSON string. Probably it is your main problem and the reason why $.get can not convert the server response to object. The objects inside the data array must be separated with commas. So the data must looks like

{
    "total": "3",
    "data": [
        {
            "id": "4242",
            "title": "Yeah Lets Go!",
            "created": "1274700584",
            "created_formated": "2010-07-24 13:19:24",
            "path": "http:\/\/domain.com\/yeah" 
        },
        {
            "id": "4242",
            "title": "Yeah Lets Go!222",
            "created": "1274700584",
            "created_formated": "2010-07-24 13:19:24",
            "path": "http:\/\/domain.com\/yeah222" 
        },
        {
            "id": "4242",
            "title": "Yeah Lets Go!333",
            "created": "1274700584",
            "created_formated": "2010-07-24 13:19:24",
            "path": "http:\/\/domain.com\/yeah333" 
        } 
    ]
}

I recommend you allays verify JSON strings in http://www.jsonlint.com/.

Oleg
Also, he hasn't told jQuery that the response is to be parsed as JSON. I believe jq defaults to expecting it to be plain text or html, so one has to add 'json' as the last argument to `$.get` (after the callback), use `$.getJSON`, or use `$.ajax` and specify `dataType:'json'`. And right, even then, if you have malformed JSON it will fail.
Alex JL
@Alex JL: You are right, of cause one should use `$.ajax` or `$.getJSON`. I personally use always `$.ajax`. I wrote the answer only because I could not read about the error in "JSON" data. It was alredy enough answers about `$.getJSON` and how to use `for` or `$.each`, so I my answer was deliberately short.
Oleg
Sure, I was just adding the information for completeness, not trying to correct you. I'm actually the one who gave you an upvote :)
Alex JL
A: 

using data from Oleg answer

var json = {} // your json data reformated by Oleg

for (var i = 0; i < json.data.length; i++) {
    document.write('<a href="' + json.data[i].path.replace(/\\/g, '') + '">' + json.data[i].title + '</a>');
    document.write('<br>');
    document.write('<p class="date">Created: ' + json.data[i].created_formated +'</p>');
    document.write('<br>');
}

remember that the "data" is an array of object

tsurahman
A: 

@Peter Ajtai

$.getJSON(base_url+'/ajax/get_itema/'+item_id+'/0/3/true', function(response) {
    $.each(response.data, function(index, value) {
        $("body").append('<a href="' + value.path + '">' + value.title + '</a>');
        $("body").append('<p class="date">Created: ' + value.created_formated + 
          '</p><br />');
    });                
});

Thanks this works, but now it appends always. When I click a link it just adds more stuff behind. What I want is to it to remove old stuff from the div and get new content in it.

Also how difficult it would be to make a pagination for it? If I get lets say 20 items and I would like to show only like 10 items per page(div)? The 0 and 3 /ajax/get_itema/'+item_id+'/0/3/true' are the limit(3) and offset(0).

mikeyy