extracting a JSON array from an API

I'm trying to extract the title from my API using JavaScript and then display it in HTML.

api:(https://k0wa1un85b.execute-api.us-east-1.amazonaws.com/production/books)

The JSON response is as follows:

{"statusCode":200,"body":[{"id":"4f160b1f8693cdbeb96ac8be135ff0f9","title":"Harry Potter"}]}

This is the JavaScript code used:

  <body>    
    <p>
        title: <span id="tit"></span><br/>
    </p>    
    <script>
        const api_url = 'https://k0wa1un85b.execute-api.us-east-1.amazonaws.com/production/books';
        async function getTitle() {
            const response = await fetch(api_url);
            const data = await response.json();

             console.log(data);

            const {title} = (data);

            document.getElementById('tit').textContent = title;
        }
        getTitle();
    </script>
  </body 

Answer №1

Here is an example of how to use it.

const api_url = 'https://example-api-url/production/data';
        async function getData() {
            const response = await fetch(api_url);
            const data = await response.json();

             console.log(data);

            const info = data.items[0].info;
            console.log(info)
            document.getElementById('inf').textContent = info;
        }
 getData();
<p>
   information: <span id="inf"></span><br/>
</p>    

Answer №2

Retrieve information from a JSON object using dot notation

async function fetchISSData() {
      const response = await fetch(api_url);
      const data = await response.json();

      console.log(data);

      const title = data[0].title;

      document.getElementById('tit').textContent = title;
}

Answer №3

One way to access the value is by using the array index as demonstrated below:

var response = {"statusCode":200,
"body":[{
"id":"4f160b1f8693cdbeb96ac8be135ff0f9",
"title":"Harry Potter"}]};
                
console.log(response.body[0].title);

var emptyResponse = {"statusCode":200,
"body":[]};
                
console.log(emptyResponse.body[0].title);

Remember to include a null check to avoid exceptions:

var response = {"statusCode":200,
"body":[{
"id":"4f160b1f8693cdbeb96ac8be135ff0f9",
"title":"Harry Potter"}]};
                
if(response.body.length){console.log(response.body[0].title);}

var emptyResponse = {"statusCode":200,
"body":[]};
                
if(emptyResponse.body.length){console.log(emptyResponse.body[0].title);}

Answer №4

Give this a shot

const api_url = 'https://74akys98h2.execute-api.us-west-2.amazonaws.com/production/books';
async function fetchData() {
    const response = await fetch(api_url);
    const data = await response.json();
    const title = data.body[0]['title'];
    document.getElementById('bookTitle').textContent = title;
}
fetchData();
<p>
    Book Title: <span id="bookTitle"></span><br/>
</p>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing Dynamic Passing of Link Element Value to a Function in jQuery

I'm working with a link element that has its value set dynamically through asynchronous means. This label's value will initially be null until it is asynchronously set by an ajax call. <a href="#" onclick="myFunction(**I want to pass the lab ...

Encountering issues with resolving dependency tree post updating node, specifically with node-sass dependency causing failure

Following the update to the latest version of Node.js, I encountered error messages when attempting to use npm audit fix --force. It appears that resolving dependency tree issues is proving to be difficult. Despite extensive research and trying various s ...

Accessing the app module in separate files is not possible for Angular and Coffeescript

As I work on managing and refactoring my Angular code in a Rails project with CoffeeScript, I am facing issues accessing Angular objects between multiple files. Here is the current file structure: javascripts |-Angular |-controllers | |-search_strl.js ...

What could be causing the header of the datatable to be out of alignment with the rest of

I'm facing an issue with my datatable where the header is misaligned with the content. Can someone please assist me in adjusting the header and content so that they are parallel? It doesn't look right at the moment. <div style="margin-top:1 ...

Is it possible to utilize a slot within a Vue.js loop?

I am encountering an issue with a template that is utilizing v-for to loop through. The template includes a named slot where the name is dynamically assigned within the loop. However, no content is displaying as expected. Can someone help me identify wha ...

A step-by-step guide to creating adorable rounded corners in a DIV element

I'd like to create a stylish rounded corner div on the top-right and top-left edges. I attempted it with the following code: border-top-left-radius: 5em; border-top-right-radius: 5em; Desired look of the div: https://i.stack.imgur.com/EoSvSm.jpg A ...

Adjusting font size in dynamic containers relatively

Imagine we have a slider named .outer, which adjusts its height based on the width of the viewport. Inside this slider, there is an example slide called .inner that contains some text. However, when we shrink the window width, the content in slide .inner s ...

JavaScript is incorrectly showing the array as empty despite containing strings

I am experiencing an issue with my array of strings in JavaScript. Despite having strings in the array when I print it in the console, the forEach function runs 0 times and JS claims the array is empty when I print its size. What could be causing this?http ...

Save user sessions in a database using node.js, express, and mongoose-auth

I have a question about authentication and sessions in node.js. So, I've set up authentication using express.js and mongoose-auth with mongodb: app.use(express.cookieParser()); app.use(express.session({ secret: 'esoognom'})); app.use(auth. ...

An intriguing inquiry regarding HTML form intricacies

Looking to enhance the source code by adding a new column to display Client Mobile, Client Office Telephone, and Client E-mail in a separate popup PHP page. My attempt involved adding a form and submit button to generate the new column. However, pressing ...

Optimizing Require.js File for Efficient Loading

I have successfully implemented require.js with multiple individual files: require(['app/login/Login'], function (app) { new app.Login(); }); Everything is functioning as expected, with each module loading when needed. Recently, I have opti ...

Unable to transform a System.String into a Class object

I'm currently facing an issue with deserializing a JSON string that I received from a Web API. try { string response = await App.client.GetUser(); App.Authentication = JsonConvert.DeserializeObject<ApiResult>(response); await Disp ...

Nest Java classes without considering their inner attributes

In managing relationships between different types in my object model, I sometimes encounter situations where references loop back on themselves. To prevent infinite recursion in scenarios like REST calls, I use annotations such as @JsonIgnore to ensure the ...

Adding a function to the Window in React & Next.js without using the onload event

Issue with External Script in React Next.js Project I am facing a problem with an external script within my React Next.js project. The script is located at . The script does not work correctly when navigating to the page using the next/link component fro ...

Send a JSON payload to a REST API endpoint using an HTML file

When attempting to send a JSON object to a RESTful web service from an HTML file, I encountered the error message "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource." Snippet of code from the HTML Ajax function: ...

Set up Vue.prototype prior to the component loading

In my Vuejs code, I am utilizing the plugins feature to define a global shared variable. Vue.use(shared) The shared variable is defined as follows:- export const shared = { config: getAppConfig() } shared.install = function() { Object.definePropert ...

The functionality of loading images with Jquery Ajax seems to only be working in Firefox. I have a feeling it may be due to a

I recently developed a web application that successfully loads images using a combination of jquery, ajax, and json. While it functions flawlessly in Firefox, Safari and Chrome present some stubborn challenges. The issue seems to stem from a "race conditi ...

Defining types for functions that retrieve values with a specified default

My method aims to fetch a value asynchronously and return it, providing a default value if the value does not exist. async get(key: string, def_value?: any): Promise<any> { const v = await redisInstance.get(key); return v ? v : def_value; } W ...

Implementing jQuery form validation including checking for the strength of the password

My understanding of jQuery was quite basic until I began working on jQuery form validation with password strength check. I successfully completed the password strength check portion, but now I am unsure of how to enable the submit button once the condition ...

The response data from the API is filled with mysterious escape characters

Obtaining data from the API response looks like this: { "ORG_ID":"165", "DEPOT_NAME":"Pesto", "DEPOT_SHORT_NAME":"PSD", "PROD_ID":"709492", "DESCRIPTION":"EX CL (2X14) U17\SH36\5", "PRICE":"3708.55 ...