Search code examples
javascriptarraysjsonobjectresponse

how i get title from following response


How i can get title or body from the following json response?

{
    "message": "All Books",
    "data": {
        "current_page": 1,
        "data": [
            {
                "id": 2,
                "title": "The Quran",
                "slug": "the-quran",
                "body": "The Holy Quran",
                "book": "/storage/books/1602685137.pdf",
                "cover": "/storage/covers/1602685137.jpg",
                "os": "both",
                "price_ios": 0,
                "price_android": 0,
                "created_at": "2020-10-14T14:18:57.000000Z",
                "updated_at": "2020-10-14T14:18:57.000000Z"
            }
        ],
        "first_page_url": "https://book.test/api/v1/books?page=1",
        "from": 1,
        "last_page": 1,
        "last_page_url": "https://book.test/api/v1/books?page=1",
        "links": [
            {
                "url": null,
                "label": "Previous",
                "active": false
            },
            {
                "url": "https://book.test/api/v1/books?page=1",
                "label": 1,
                "active": true
            },
            {
                "url": null,
                "label": "Next",
                "active": false
            }
        ],
        "next_page_url": null,
        "path": "https://book.test/api/v1/books",
        "per_page": 15,
        "prev_page_url": null,
        "to": 1,
        "total": 1
    }
}

Solution

  • Assuming your JSON is assigned to a variable called response you can access the body with:
    let body = response.data.data[0].body

    And the title with
    let title = response.data.data[0].title

    In case you want to loop over the data array in order to get a value for all entries (e.g. title), try this:
    let titles = response.data.data.forEach(entry => console.log(entry.title));