So im trying to load a .json file into a SharedArray
according to the docs here: https://k6.io/docs/javascript-api/k6-data/sharedarray/
Right now my "load" function looks like this:
export function loadData(dataFile) {
const data = new SharedArray('dataFile', function () {
const obj = JSON.parse(open(dataFile));
return obj;
})
return data
}
Which I then load in my test file via:
const data = loadData("/resources/api/cloud-pos-check/cloud-post-check.json");
const body = data[0];
(data[0] above is the JSON object in the JSON file, it is the only object there in that .json file)
It was failing until I realized that what I am sending via the payload was a JavaScript Object/String and NOT actual JSON.
So I have to do JSON.stringify(body)
for the payload. Which seems silly because I am opening a JSON file, parsing it to a string then re-converting it to JSON. I guess what I want to know is this necessary?
Can SharedArray HOLD an actual .json value? Or do I need to do what I am doing everytime I need to send an actual .json payload. FWIW If I try to read directly the object that open returns it shows as blank in the console.
Thanks
SharedArray
can only store a single array (as the name implies). But nothing stops you from wrapping arbitrarily-complex objects or literals in a single-element array:
const shared = new SharedArray('dataFile', function () {
const myobj = { "a":42, "nested": { "list": [ 1, 3, 3, 7 ] } };
return [ myobj ];
});
And then access your object with shared[0]
:
const myobj = shared[0];
console.log(myobj.nested.list[1]); // 3
For your specific use case:
export function loadData(dataFile) {
const data = new SharedArray('dataFile', function() {
return [ JSON.parse(open(dataFile)) ];
})
return data;
}
or even:
export function loadData(dataFile) {
const data = new SharedArray('dataFile', function() {
return [ JSON.parse(open(dataFile)) ];
})
return data[0];
}
Note that SharedArray
instances can only be constructed in the init context.