What is the method for accessing JSON data?

Looking for assistance on a coding issue I'm facing. I need my JavaScript code to read JSON data and grant access to a staff panel based on the information provided. Below is the sample JSON:

{
    "User1": {
        "User": "Elliott",
        "StaffPanelAdvanced": "true"
    },
    "User2": {
        "User": "Max",
        "StaffPanelAdvanced": "true"
    },
    "Password:": "2201-hrstaffpanel"
}

My current JavaScript code snippet is as follows:

let pr = prompt("What is your staff name? (Case Sensitive)")
                    if (pr === data.User1.User) {
                        alert("Logged in successfully, " + pr + ".")
}

(Note: I am using 'fetch' to retrieve the JSON info due to issues with 'require'.) Can someone please help me figure out why this setup is not functioning correctly?

Answer №1

When utilizing the fetch function, make sure to properly parse the JSON response into an object.

      fetch('api-url')
        .then((response) => {
          if (!response.ok) {
            throw new Error(response.statusText)
          }
          return response.json() // Convert response to JSON object
        })
        .then((data) => {
           // You can now access the data as an object.
           console.log(data)
        })

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

I attempted to add the maatwebsite/excel package to my Laravel project, but encountered a error during installation

I attempted to add the maatwebsite/excel package to my Laravel project using the command: composer require maatwebsite/excel However, I encountered an error message that stated: Your requirements could not be resolved to an installable set of packages. ...

Typescript is throwing a fit over namespaces

My development environment consists of node v6.8.0, TypeScript v2.0.3, gulp v3.9.1, and gulp-typescript v3.0.2. However, I encounter an error when building with gulp. Below is the code snippet that is causing the issue: /// <reference path="../_all.d. ...

When using Laravel's @json in blade, the output is encoded, but the dump function displays the correct result

Greetings, my dear friends. I don't post very often, but I'm reaching out because I am struggling with a current issue that is causing me pain. I have attached some pictures to help illustrate the problem. Essentially, when I create an array for ...

There appears to be an issue with the functionality of the Bootstrap toggle tab

Currently, I am facing a toggle issue and having trouble pinpointing the root cause as there are no errors appearing in the console. The problem involves two tabs that can be toggled between - "pay" and "method". Initially, the default tab displayed is "pa ...

Error encountered due to WCF's JSON error handler triggering an exception

In the endpoint configuration, I have set up two behaviors: The first behavior is for json serialization and it closely resembles the example provided here. The important part of this behavior is as follows: public class NewtonsoftJsonBehaviorExtensio ...

Customizing blockquote styling in QuillJS with a unique class

Currently, I am exploring a method to include a custom class when the user selects the blockquote toolbar button. When the blockquote is clicked, it generates the following element: <blockquote class="ql-align-justify">this is my quoted tex ...

Utilizing Selenium in Python to Scroll within Inner Div: A Guide

Curious about how to scroll through the chats on web.whatsapp.com? Check out the pseudo-code below: recentList = driver.find_elements_by_xpath("//div[@class='_2wP_Y']") driver.execute_script("window.scrollTo(0, 500);") I'm eager to find a ...

The for loop does not cycle through every element

I'm working on a class project that involves creating custom HTML tags with JavaScript. I have a for loop set up to iterate over each use of the tag, but for some reason, it only seems to loop over every other tag. I'm specifically trying to crea ...

Problems encountered when attempting to create a link between two nodes on a force-directed graph using a mouse click

I'm currently working on creating an interactive graph where users can click on two nodes to establish a link between them (which can be removed later). My approach was inspired by Mike Bostock's example at: https://bl.ocks.org/mbostock/1095795 ...

Tips for utilizing browser cache in AJAX requests to prevent loading the refreshed JSON file

It may seem like a strange question, but I'm experiencing an issue with an AJAX call to a JSON file. Both the request and response headers do not indicate to not use cache, and in the browser settings, the Disable cache option is not checked. What mor ...

Plot data points from geojson onto a leaflet map using markers

How can I efficiently import geoJson data (containing over 2000 coordinates) into a leaflet map? Below is a brief snippet of geo json: { "type": "FeatureCollection", "features": [ { "type": "Feature", "geometry": { ...

Creation of source map for Ionic 2 TypeScript not successful

Struggling with debugging my Ionic 2 application and in need of guidance on how to include souceMap for each typescript file that corresponds to the javascript files. Despite enabling "sourceMap":true in my tsconfig.json file, the dev tools in Chrome do n ...

Determining array size with the help of a jsonpath expression - The expert in JsonPath, Stefan

Currently, I'm facing an issue while attempting to determine the size of an array or list using Stefan Goessner's JsonPath. The version I am utilizing is json-path-2.0.0. My JsonPath expression is $.orders.length and the JSON data resembles the ...

Having trouble fetching JSON data using AJAX

Having trouble retrieving Json text from servlet response. The servlet code is functioning properly. It seems there may be an issue with my Ajax code. It doesn't seem to return anything. Do I need a specific jar file for this task? Below you can find ...

"Exploring the Versatility of Polymorphism in JSONModel for

Exploring the best practices of showcasing polymorphism within JSONModel using specific models as examples. @interface GameModel : JSONModel @property (nonatomic, assign) long id; @property (nonatomic, assign) NSArray<GameEventModel> *events; /* . ...

Ajax: Failed to send POST request (404)

After adding a POST script in the manage.ejs file and console logging the data to confirm its functionality, I encountered an issue. Below is the code snippet: <script type="text/javascript"> var guildID = "<%= guild.id %>"; let data = {so ...

Looking for assistance with creating a D3 bar chart that involves selecting a specific year and crime category? Let me help

I am still learning D3 and I'm facing a challenge while trying to create a bar chart. My idea is to first select the YEAR radio button, then choose the CRIMEHEAD option, and finally the bar chart should be displayed. Here's my thought process: I ...

Rendering JSON data in the browser to display an order

I have discovered that when requesting JSON, the default order cannot be expected. I noticed this while using an API I created where the elements returned were in a random order each time I made a new call. How does a site like Ticketfly's API (you c ...

Array containing two objects in a two-dimensional format

In the example provided, I am working with a 2D array. Link to the example: https://codesandbox.io/s/v0019po127 I am noticing different results depending on whether I use the browser console or Codesandbox's console. I have attempted using JSON.str ...

What is the process for changing a DynamoDB table from PROVISIONED to PAY_PER_REQUEST using Node.js?

Currently, I have a DDB table set up with BillingMode: PROVISIONED and ProvisionedThroughput:{...}. My goal is to switch it to BillingMode: PAY_PER_REQUEST, but every time I attempt this change, I encounter the following error: TypeError: Cannot read prop ...