I'm currently using an API and getting the following results for my GET request:
[{"id" : 123456, "title" : "hello world", "post" : "this is the actually text of the blog"}, {"id" : 123457, "title" : "hello world 2", "post" : "this is the second blog post"}]
I want to be able to get each title & post, but my basic knowledge of JSON would tell me that I need to declare each part of the array, like this:
["data" : {"id" : 123456, "title" : "hello world", "post" : "this is the actually text of the blog"}, "data" : {"id" : 123457, "title" : "hello world 2", "post" : "this is the second blog post"}]
Does anyone have any ideas as to how I can iterate through this into HTML?
Thanks.
The first one is an array containing two objects, the second is an array with a named object, containig two child objects. Your second example won't work, because you're assigning array elements names (data, post) while arrays are auto-indexed with integers. The syntax is simply invalid.
Using the result you get from the API, you first need to convert it into an object.
resultObject = JSON.parse('[{"id" : 123456, "title" : "hello world", "post" : "this is the actually text of the blog"}, {"id" : 123457, "title" : "hello world 2", "post" : "this is the second blog post"}]');
After this, you can simply iterate over the array:
resultObject.forEach(function(e) {
console.log(e.title + ": " + e.post);
});
The above will output
hello world: this is the actually text of the blog
hello world 2: this is the second blog post
Here is a working jsfiddle of the solution at http://jsfiddle.net/4WxFk/3/
<div id="response"></div>
<script>
var res= '[{"id" : "123456", "title" : "hello world", "post" : "this is the actually text of the blog"}, {"id" : "123457", "title" : "hello world 2", "post" : "this is the second blog post"}]'
var pres = JSON.parse(res)
$.each(pres, function(){
console.log(this)
$("#response").append(this.id + ","+ this.title + "," + this.post)
})
</script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.