Riffaz Starr
Riffaz Starr

Reputation: 611

How to get the Json object array value?

I am trying to display a list of posts using json and jquery.

This is what I am using to fetch the data

var app = {

    init: function() {
        app.getPosts();
    },

    getPosts: function() {

        var rootURL = 'https://www.example.com/wp-json/wp/v2/posts';

        $.ajax({
            type: 'GET',
            url: rootURL,
            dataType: 'json',
            success: function(data){

                $.each(data, function(index, value) {
                    console.log(value.featured_image);
                  $('ul.topcoat-list').append('<li class="topcoat-list__item">' +
                    '<h3>'+value.title+'</h3>' +
                    '<p>'+value.excerpt+'</p></li>');
                    ;
                });
            },
            error: function(error){
                console.log(error);
            }

        });

    }

}

but this code just returns following output

but when I go to https://www.example.com/wp-json/wp/v2/posts I see the perfect array.

the example of an array there

{
    "id":2267,
    "type":"post",
    "title":{"rendered":"When to visit Arugam Bay? &#8211; Arugam Bay Weather &#038; Seasons \u2013"},
    "content":{"rendered":"<div class=\"circle-headline\">\n<p>The right answer is<\/p>\n<\/div>\n<p class=\"wpk-circle-title text-custom\">ALL YEAR LONG!<\/p>\n<p>You can visit Arugam Bay anytime and always find amazing sunny weather. Despite this incredible where, there is a high and low season.<\/p>\n","protected":false},
    "excerpt":{"rendered":"<p>The right answer is<\/p>\n<p>ALL YEAR LONG!<br \/>\nYou can visit Arugam Bay anytime and always find amazing sunny weather. Despite this incredible where, there is a high and low season.<\/p>\n","protected":false},
    "author":1,
    "featured_media":2268,
    "comment_status":"open",
    "ping_status":"open",
    "sticky":false,
    "template":"",
    "format":"standard",
}

How can I get the title and excerpt from there and show a list using it?

Upvotes: 1

Views: 94

Answers (1)

Harald Gliebe
Harald Gliebe

Reputation: 7554

Access the rendered property that contains the actual string:

'<h3>'+value.title.rendered+'</h3>' +
'<p>'+value.excerpt.rendered+'</p></li>');
...

Upvotes: 4

Related Questions