Skip to content Skip to sidebar Skip to footer

How To Parse Json String To Javascript Object

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.c

Solution 1:

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.

Solution 2:

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"...

Solution 3:

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/.

Solution 4:

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.

Solution 5:

using data from Oleg answer

var json = {} // your json data reformated by Olegfor (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

Post a Comment for "How To Parse Json String To Javascript Object"