Friday, 28 April 2017

JavaScript parse JSON











I have this JSON string:




[{"title": "Title1"}, {"title": "Title2"}]


How can I parse it, so that I can get each title?


Answer



var string = '[{"title":"Title1"},{"title":"Title2"}]';

var array = JSON.parse(string);
array.forEach(function(object) {

console.log(object.title);
});


Note that JSON.parse isn't available in all browsers; use JSON 3 where necessary.



The same goes for ES5 Array#forEach, of course. This is just an example.



If you're using jQuery, you could use $.each to iterate over the array instead. jQuery has a jQuery.parseJSON method, too.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...