Check field from JSON response

Hi,

I’m trying to check a specific field from JSON response, unsuccessfully.
Could you, please, provide any advise?

My intention is to check whether the field ‘id’ is contained in the JSON response, “id”: “12123-24H-MADRID”.

TEST CASE

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

export default function () {
    const url = 'http://localhost:8080/offer-evaluate';
    let headers = { 'Content-Type': 'application/json' };
    let data = {
        "offerExternalId": "ashgGGHgGH02",
        "offerId": "12123",
        "rateModelId": 1,
        "version": 1,
        "rateModelDesc": {
          "key": "TARIFF_STANDARD"
        }
 };
  
    let res = http.post(url, JSON.stringify(data), { headers: headers });
     check(res, {
      "status is 201": r => r.status === 201,
      "id": r => r.json()["id"] === "12123-24H-MADRID"
    });
}  

RESPONSE JSON

[
    {
        "id": "12123-24H-MADRID",
        "tariffModelId": "12123",
        "productId": "24H",
        "origin": {
            "name": "MADRID",
            "regexpr": null,
            "code": "ES-M",
            "scales": null
        }
]

Your response appears to be an array of JSON objects (judging by the presence of square brackets), so to access the id property of the first object in the array, you would need to do something like res.json()[0]["id"] or res.json()[0].id.

3 Likes

You nailed it!. It works just fine, thanks a lot mate. I really appreciate your help.