Example of using a json data file

Hi,
A newbie to k6, just start two days back :). I was trying to setup a load test with json data file. How do i iterate thru the json data file. Appreciate a small example.
Json Data file content

{

  "appRequest": [
      {
        "memberId": "00000297800",
        "fromDate": "2015-07-01",
        "throughDate": "2015-07-02"
      },
      {
        "memberId": "00000297810",
        "fromDate": "2016-01-01",
        "throughDate": "2199-12-31"
      }
  ]
}

js file content

import { check } from "k6";
import { SharedArray } from 'k6/data';
import http from 'k6/http';

const data = new SharedArray("memberprofile", function() { return JSON.parse(open('./data.json')).appRequest; });

export let options = {
  stages: [
      // Ramp-up from 1 to 5 virtual users (VUs) in 5s
      { duration: "5s", target: 2 },

      // Stay at rest on 5 VUs for 10s
      { duration: "10s", target: 2 },

      // Ramp-down from 5 to 0 VUs for 5s
      { duration: "5s", target: 0 }
  ]
};

export default function () {
  var url = 'http://localhost:9080/mbrProfCntx/v5/memberprofile';
  var payload = **"How do I iterate thru the payload"**
  var params = {
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
    },
  };

  http.post(url, payload, params);

  });
}

Thanks
Raj

export default function () {
  var url = 'http://localhost:9080/mbrProfCntx/v5/memberprofile';

  var payload = data[Math.floor(Math.random() * data.length)];

 // console.log(JSON.stringify(payload),null,2);
  
  var params = {
    headers: {
      'Content-Type': 'application/json',
    },
  };

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

      // Verify response
  check(res, {
    "status is 200": (r) => r.status === 200,
  });

  sleep(Math.random() * 2);
}

Hi Raj,
Welcome to the k6 community forum.

I’m happy you already found a solution, I provide one more alternative.
Considering the response and the original example you posted seems you need a method for picking an item from the SharedArray using a dynamic index without specific restrictions. As you have seen, a SharedArray can be accessed like a native JS array.
If the randomness is not a strict requirement then you could consider using the execution context __ITER variable. If you expect a data.length smaller than iterations use it with a modulo function.

Here an example:

var payload = data[__ITER % data.length] 

I would also encourage you to read the When parameterizing data, how do I not use the same data more than once in a test? - #2 by mark thread where there are explained more advanced use cases and details for the same class of your question.

Thanks Ivan, will look into it.