What is the best way to retrieve data from a JSON file in order to display it in the inner HTML of a webpage

I'm encountering an issue when trying to extract data from a JSON file. I attempted to use the .map() function to map out the data, but I keep receiving an error stating that result.map() is not a defined function. How can I properly extract this data?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>JSON Test</title>
</head>
<body>
    <div id="myData"></div>
        <!-- Here a loader is created which 
             loads till response comes -->
        <div class="d-flex justify-content-center">
            <div class="spinner-border" 
                 role="status" id="loading">
                <span class="sr-only">Loading...</span>
            </div>
        </div>
        <h1>Registered Employees</h1>
        <!-- table for showing data -->
        <table id="employees"></table>
    </body>
    <script src="api1-2.js"></script>
</html>

Answer №1

Make sure to utilize response.json() instead of response.text().

Both response.json() and response.text() return a Promise, however, response.json() resolves that Promise to a JavaScript object while response.text() resolves it to a String.

Further reading:

Answer №2

To convert the API response to a JSON object, replace response.txt() with response.json(). If you use response.text(), the result will remain as a string and not have the map method, resulting in an undefined error.

fetch("https://v1.nocodeapi.com/OPENSOURCE12/instagram/gflSSOQjdOHsVnhT", requestOptions)
    .then(response => response.json()) // 👈 make this change
    .then(result => {console.log(result)})
    .catch(error => console.log('error', error));

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

Scala.js introduces a powerful feature called Scala.js yields, which

Currently, I am utilizing Transcrypt to convert Python code into Javascript. This allows me to incorporate generators in Python, such as: def color(): colors = ["red", "blue", "yellow"] i = -1 while True: i += 1 if i >= colo ...

How can I effectively make properties accessible in my template to facilitate form validation in Angular?

Scenario: I'm facing a situation in my Angular project where I have a LoginFormComponent. This component has a form with two properties: email and password. My goal is to create properties within this component that can be accessed in the template. Th ...

How to make an AJAX request in jQuery / JavaScript after a specific time interval has passed

Here is the code snippet I'm working with: $('input.myinput').each(function(){ var id = $(this).val(); var myajax = function(){ $.ajax({ url: ajax_url, type: "GET", data: ({ code: id ...

What is the best way to arrange these divs one on top of another?

I have combed through numerous resources but still haven't found a solution to my problem. I am struggling with figuring out how to stack the "top_section" div on top of the "middle_section" div. Currently, "middle_section" is appearing above "top_sec ...

The "client-side rendering" directive in Next.js layout.tsx causes issues on mobile devices

I'm currently in the process of implementing an auth context into my next.js application. Here's the snippet of code residing in my layout.tsx file: "use client"; import './globals.css' import type { Metadata } from 'nex ...

Angular 2 table fails to refresh after callback updates collection, but a timer update triggers a full refresh of the collection

I am experiencing an issue with updating a string[] collection from the Observable subscription: heroes:string[] = ['milan']; // this works fine let current = this; (function theLoop (i: number) { setTimeout(() => { current.heroe ...

What steps can I take to tackle this issue using JavaScript?

We are currently working with an array that contains a list of various website names. Some examples include www.google.com, www.msn.com, www.amazon.co.in, in.answers.yahoo.com, en.m.wikipedia.com, codehs.gitbooks.io,www.coderanch.com, and more. Our goal is ...

Is it possible to modify the object's key value when generating an array value with the map function in React?

I have the array object data stored in a variable called hi[0].child. hi[0].child = [ {code: "food", name: "burger"}, {code: "cloth", name: "outer"}, {code: "fruit", name: "apple"}, ] ...

Shifting Icon to the Right within the Drawer Navigator Toolbar

While modifying the example code for Material UI's drawer navigator, I decided to enhance it by adding a notification icon and a checkout icon with the Admin Panel typography in the toolbar. However, I encountered an issue where the checkout icon app ...

Refresh needed for Jquery Menu icon changes to take effect

My goal is to create a 'slide toggle menu' where the menu icon changes to a 'close' symbol every time it is clicked to open, and then reverts back to normal when clicked to close. However, I'm facing an issue where this functionali ...

What steps can be taken to eliminate the undefined error in AngularJS?

Seeking assistance on resolving the undefined error in AngularJS. I am attempting to fetch data using resolve and utilize it in the controller, but I keep encountering an undefined message. Any insights on why this is happening? resolve: { message: fu ...

Saving vast array in MongoDB

I am currently working on a personal project that involves implementing a search feature. My setup includes using typeahead.js with a REST api created in expressJS and mongoDB. I could use some guidance on two particular challenges I am facing. While my ba ...

Modifying the key of a JSON file

One of the challenges I'm facing involves handling a JSON file that is being inserted into MongoDB. "entities": [{ "desctype": "Location", "text": "Marília", "relevance": 0.966306, "disambiguation": { "subtype": [ "City ...

Embrace the functionality of zooming and dragging on jVectorMap for a seamless user

Are there built-in methods in jVectorMap to control map zooming and dragging with the mouse? I couldn't find them in the documentation. I am looking to achieve something similar to this: var map = $('#world-map').vectorMap(); map.on(&apos ...

Error occurs in Windows script while running a project installed globally

Upon installing my project globally, I encountered a Windows Script Host error. https://i.stack.imgur.com/unFVu.png What steps can I take to resolve this issue? The following is my JavaScript code snippet: Object.defineProperty(exports, "__esModule ...

Creating dual permission menus for two different roles in Vue JS 3

This is my router file checking which role is logged in: router.beforeEach((to, from, next) => { if (to.matched.some(record => record.meta.requiresAdmin)) { if(VueJwtDecode.decode(localStorage.getItem('accessToken')).sub == &quo ...

The JsFiddle code is malfunctioning

One question I have is about preparing a JSFiddle for a small click program which is not working. It consists of just two lines of code. HTML <body> <button onclick="javascript:launchdialog();">Click Me</button> </body> JavaS ...

Using CSS alone to maintain responsive aspect ratios: A solution to filling container heights

I'm trying to find a way for an inner div to fill the height of its container with a fixed aspect ratio of 1:1. The usual method using padding works great for filling the width, but not so much for the height. Is it possible to achieve this purely wi ...

Preventing multiple clicks by toggling the HTML tag on and off

Here is the jQuery structure that I am currently working with: $(document).on('click', '.view-details', function () { $(this).prop("disabled", true); // API call1 // API call2 // API call3 $(this).prop("disabled" ...

"Commitment made ahead of time without allowing for the outcome to

I'm completely new to working with promises and I'm encountering some unexpected behavior in my code. The issue lies in the TaskRunner.SyncObjects function within Main.js, which should be waiting for the selectedCourses variable to be populated ...