Home > database >  Unfolding JsonArray Response object
Unfolding JsonArray Response object

Time:06-25

So I am trying to unravel my response from a fetch:

  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 unpack the response as a json with response.json. Then I console.log to my browser, and the (raw) response in the console is as such: 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":"[email protected]",
         "string":"[email protected]",
         "valueType":"STRING"
      },
      "naam":{
         "chars":"CrazyDiamond",
         "string":"CrazyDiamond",
         "valueType":"STRING"
      },
      "hoeveelheid zoekopdrachten":{
         "integral":true,
         "valueType":"NUMBER"
      }
   }
]

Am I correct in saying that it looks to be an array containing JsonArray objects, containing json objects?

My question is how do I reach this objects individually in a console.log(xxx); ?

EDIT: This is what the rest service on the other side, I have access to both:

            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();
        }

CodePudding user response:

log object in a formatted way using JSON.stringify

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

or in your specific case, use this:

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