Response.json( [selector] ) getting undefined

Hi,
I am getting undefined when using
console.log(JSON.stringify(getUserResponse.json()[0]));

but it works fine if I use: console.log(JSON.stringify(getUserResponse.json()));

.

import http from "k6/http";
import { check, sleep } from "k6";

// Common things
const API_URL = "https://gorest.co.in/public/v1/users";

// Test setup
export let options = {
    vus: 1, duration: '1s'
};
// Test scenario
export default function () {

    // Common requests params
    const params = {
        headers: {
          'Content-Type': 'application/json',
        },
      };

    // get user
    let getUserResponse = http.get(
        `${API_URL}`,params
    );
    check(
        getUserResponse,
        { "Get user response status code is 200": (r) => r.status == 200 }
    );
    console.log(JSON.stringify(getUserResponse.json()[0]));

    // Short break between iterations
    sleep(1);
}

why it does not work using console.log(JSON.stringify(getUserResponse.json()[0]));?


Hi @fatkobra,

From what you’ve given us, it seems, like you have an object and you are getting that objects 0 field. Which just doesn’t exist so you get undefined.

I expect that you expected an array and wanted the first element?

Hi @mstoykov ,

yes how do I access the first, second, and so on elements?

Thank you so much for replying.

What you have done would’ve given you the first element of an array, but response is not an array. If you want the first element of the data field of the response than getUserResponse.json().data will give you the data so getUserResponse.json().data[0] should be the first element.

Thank you so much @mstoykov ,

It works fine,

I am sorry to ask again!

I tried the same concept (console.log(JSON.stringify(res.json().data[0]));) using a POST method and I am getting the following error:

ERRO[0001] TypeError: Cannot read property '0' of undefined

What am I missing?

Here is my full code:

import http from "k6/http";
import { check, sleep } from "k6";

// Common things
const url = "https://reqres.in/api/users";

// Test setup
export let options = {
    vus: 1, duration: '1s'
};

// Test scenario
export default function () {

    const params = {
        headers: {
          'Content-Type': 'application/json',
           
        },
      };
    
      const postdata = {
        "name": "Ramon",
        "job": "roboteiro"
    };

    let res = http.post(url,JSON.stringify(postdata),params);
    check(res, { 
        "Create user response status code is 201": (r) => r.status == 201, 
        }
    );
    
    sleep(1);
    console.log(JSON.stringify(res.json().data[0]));
}

If you look at the response it obviously doesn’t have data element so then res.json().data is undefined (along the same way that it previously res.json()[0] was - there is no such element).

In this case I just don’t know what you would want to console.log, but the errors is correct. If you are doing this for debugging purposes I would recommend just console.log-ing res.json() and look at the whole response.

Hey @mstoykov ,

appreciate your patience. I am still a newbie.

Using console.log(JSON.stringify(res.json())); I do get a response. See attached with --debug and without.

Using console.log(JSON.stringify(res.json())); I do get a response. See attached with --debug and without.

Yeah, which seems okay - this is what the API returns. Are you worried about that? Because this likely need to be discussed with whoever is writing the API. The response seems to be a succesful one and if it’s missing something you expect - that might be a bug.

1 Like

Hi @mstoykov ,

Thanks for getting back to me.

My ultimate goal is to learn how to parse the values of one element (just 1) of the JSON object response to another POST request.

let res = http.post(url,JSON.stringify(postdata),params);

let res1 = http.post(url,JSON.stringify(res.json().data[0]["transfer"]),params);

Something like the above.

My ultimate goal is to learn how to parse the values of one element (just 1) of the JSON object response to another POST request.

What you are doing is what you need to do :tada: . You just now need to figure out how to get the exact element you want and as far as I can see the problem resolves around:

  1. You don’t know what you have in the response. Logging the response once and seeing what it has fixes that
  2. You have some problems with selecting that element. There is some MDN JSON doc which seems relevant. Also (as you seem to get your elements only from responses) use the built into response.json() selector, with it’s syntax defined here. With an example from above res.json("data.0.transfer") - this is probably going to be somewhat more performant and also might read nicer in some cases :man_shrugging: .

Also of note is that you probably should check response.status as if the server returned 4xx or 5xx status it is likely the response will not be json at all and you will get an exception.

Hope this helps you

2 Likes

Thank you so much @mstoykov for your help and guidance :clap:.

Point 2 was spot on :grinning: