Exploring the JsonArray Response entity

Trying to decode my fetch response:

  fetch('restservices/users/', fetchOptions)
    .then(function (response) {
      if (response.ok) {
        console.log('1');
        console.log(response)
        const responseSjon = response.json()
        console.log('2');
        console.log(responseSjon);
        console.log('3');
        // console.log(JSON.stringify(responseJson, null, 2));
        console.log(JSON.stringify(responseJson));
        console.log('4');

In my JavaScript, I parse the response as JSON using response.json. Then I log to my browser, and the (raw) response in the console is shown below: enter image description here

[
   {
      "email":{
         "chars":"CasaSuCasa",
         "string":"CasaSuCasa",
         "valueType":"STRING"
      },
      "naam":{
         "chars":"Coyote",
         "string":"Coyote",
         "valueType":"STRING"
      },
      "hoeveelheid zoekopdrachten":{
         "integral":true,
         "valueType":"NUMBER"
      }
   },
   {
      "email":{
         "chars":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6a19130e2a080b18180f1e1e44090507">[email protected]</a>",
         "string":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="72010b1632101300001706065c111d1f">[email protected]</a>",
         "valueType":"STRING"
      },
      "naam":{
         "chars":"CrazyDiamond",
         "string":"CrazyDiamond",
         "valueType":"STRING"
      },
      "hoeveelheid zoekopdrachten":{
         "integral":true,
         "valueType":"NUMBER"
      }
   }
]

Is it correct to assume it's an array with JsonArray objects, each containing JSON objects?

My question is how can I access these objects individually in a console.log(xxx); ?

EDIT: This is the code for the rest service on the other end, which I have access to:

            Map<String, User> commune = Community.getUserMap();
            JsonArrayBuilder jab = Json.createArrayBuilder();

            JsonObjectBuilder job = Json.createObjectBuilder();
            commune.forEach((key, user) -> {

                job.add("email", user.getEmail());
                job.add("naam", user.getNaam());
                job.add("role", user.getRole());
                job.add("hoeveelheid zoekopdrachten", user.getAlleZoekertjes().size());
                jab.add(job);
            });
            return ok(jab.build()).build();
        }

Answer №1

Display the log object in a structured format by using JSON.stringify

console.log(JSON.stringify(userResponseJson, null, 2));

Alternatively, for your specific scenario, you can do the following:

fetch('restservices/users/', fetchOptions)
.then(userResponse=>userResponse.json())
.then(userResponse=>console.log(JSON.stringify(userResponse, null, 2)))

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

Transform a Vue JS Typescript object into an array and then back into an object through iteration

Having an object that contains an array of objects, I am looking to extract the data from each object in the array to show the opening hours. I have successfully accessed each key value within a for loop in the code snippet. However, I am unsure about how ...

Ways to navigate private property using the App Component in Angular 4

I have successfully implemented code in my app component to retrieve the current URL and display it in app.component.html. app.component.ts import { Component } from '@angular/core'; import { Router } from '@angular/router'; @Compone ...

Update data in several JSON files with extensive sizes

I have a directory filled with numerous large JSON files that I want to enhance for better performance. My approach involved utilizing the gulp tool along with gulp-replace to eliminate unnecessary white space. Within these files lies a significant JSON s ...

Creating a custom JavaScript clock based on stored database values

I am looking to create an analog clock using JavaScript. I have both working hours and off hours stored in a database. My goal is to display working hours in one color and off hours in another color on the clock. How can I achieve this? The database prov ...

What is the best way to execute useEffect in React Router?

Struggling to get my useEffect function to run properly in a React app using a REST API for a Inventory Management application. The issue seems to be with setting the item variable. Any insights on why this might be happening? Item.jsx: import React, { us ...

Retrieve the object from the PHP array of objects by searching for the one with the ID equal to 2

Within the "list_member" class, I have defined various attributes such as $id, $email, $lastchange, $active, $hash, and $list_id. class list_member { public $id; public $email; public $lastchange; public $active; public $hash; public $list_id; ...

Bootstrap: when divs cover the jumbotron

I have recently started exploring bootstrap and have been using it to build a homepage for my website. However, I am facing an issue: The three images are overlapping the jumbotron section and I can't seem to figure out why. Below is the HTML code sn ...

Utilizing BBC gelui within Joomla 3.0 for seamless integration

I am currently using Joomla! 3.0 with the Joomlashape Helix template and I am following a tutorial. You can check out the tutorial here. The tutorial mentions that I need to download RequireJS. Can anyone confirm if RequireJS is compatible with Joomla 3 ...

When the parent element's CSS property is set to display: none, ng-repeat fails to function

I have a division with a specific class in the CSS named display: none;. When I click on a button, I switch the class using a toggle class feature called ng-class="vm.showing ? 'zoomIn' : 'zoomOut'". The issue arises when Angular does n ...

Visual Matrix and Directional Controls

I'm currently learning JavaScript and I've put together this script from different sources to help me grasp the basics. I prefer to keep it simple and would appreciate explanations if it gets too complex. Don't assume I know too much about i ...

Steps for declaring an array in the C programming language

Currently, I am engrossed in the enlightening book "Cracking the Coding Interview," which unveils insightful examples of algorithms in C. Enthused by the prospect of learning, I aspire to craft programs that bring these algorithms to life and analyze their ...

Retrieving Information from a JSON Object using Angular 2

I'm dealing with a JSON object response. The object looks like this: {auth_token: "60a483bc0b1bc4dc0231ff0b90a67be1dad6ef45"} auth_token:"60a483bc0b1bc4dc0231ff0b90a67be1dad6ef45" proto : Object My goal is to extract the value "60a483bc0b1bc4dc0231f ...

The Problem with AJAX Error Handling Customization

Upon loading my webpage using Code Igniter and PHP, the JSON encoded query is returned successfully with data. I have managed to handle the scenario where no records are found by encoding a response in JSON format. However, I am unsure of how to transmit t ...

Guide to making control bar fade out when video is paused on video.js

Is there a way for the control bar to automatically disappear when the video is paused? Thank you in advance! ...

5% of the time, Ajax fails and the response is "error"

When utilizing jQuery for Ajax calls, I have encountered a situation where the call fails approximately 5% of the time. To troubleshoot and understand the issue better, I implement this code: $.ajax({ type:'POST', url:'somepage.php ...

Type casting with Numpy inplace

Working with a numpy array phase of floats, specifically with dtype=np.float32, I need to convert it to integers, denoted as out and having dtype=np.uint8. It's important that this conversion occurs in-place due to speed considerations. While attempt ...

Filtering JSON data becomes seamless with the use of AngularJS

Is there a way to pass JSON data obtained from services.js to filter.js for filtering purposes? For instance: JSON data: {"name" :"stackoverflow"} Services.js: Created a service to retrieve JSON data {"getjsondataservice" } Controller: Acce ...

JSON.Net appears to incorrectly validate a schema using anyOf in cases where it should not

My current task involves detecting whether the user has input a boolean as a string rather than an actual boolean value. To test this, I am examining the commentsModule/enabled property to see if the value is false, once surrounded by quotes and once witho ...

Dealing with a throw er; uncaught 'err' event while configuring a server with nodemon

I am currently in the process of setting up my local server using node.js and nodemon. Initially, everything runs smoothly on localhost, but as soon as I refresh the page or navigate to another page, the server crashes with an 'unhandled error event&a ...

Node is looking for a callback function, but instead received something that is undefined

When attempting to build a basic CRUD app in node js, an issue arises with the error message "Route.get() requires a callback function but got a [object Undefined]" specifically on the router.get("/:id", userController.getUser); line. Routes.js const expr ...