"Unexpected token, expected" when I tried to get value from .json file for k6 script JS

84 Views Asked by At

I have a JSON file with some values

{
    "1": "socks",
    "2": "jeans",
    "3": "hoody"
}

I'm trying to get random value from this file

import { sleep, group, check } from "k6";
import http from "k6/http";
import { checkCode } from "./mainFunction.js";
import searchWords from "../data/searchWords.json";


let duration='1m';
let maxVUs = 100;
let randomNumber = function (min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min);
};
let response;
let searchId = randomNumber(1, 27);
let searchWord = searchWords[searchId];
let searchUrl = encodeURIComponent(searchWord);

and when I run a script I got error and I don't understand how to fix it

ERRO[0000] SyntaxError: file:///Users/malekulo/Testing/data/searchWords.json: Unexpected token, expected ; (2:7)
  1 | {
> 2 |     "1": "socks",
    |        ^
  3 |     "2": "jeans",
  4 |     "3": "hoody"   
    at <internal/k6/compiler/lib/babel.min.js>:7:10099(24)
    at <internal/k6/compiler/lib/babel.min.js>:5:29529(56)
    at h (<internal/k6/compiler/lib/babel.min.js>:4:30563(6))
    at bound  (native)
    at s (<internal/k6/compiler/lib/babel.min.js>:1:1327(8))  hint="script exception"
1

There are 1 best solutions below

0
Михаил Стойков On

k6 does not support importing json.

You can use open and get the same thing though as in

const searchWords = JSON.parse(open("../data/searchWords.json"));

Just be careful as this file will be open and loaded for each VU you have, so if it is 1mb file and you have 1000 VUs it will use a lot more than 1GB of memory as it also needs memory for the objects.

If the file is a big array you can use SharedArray as in

import { SharedArray } from 'k6/data';
const searchWords = new SharedArray('searchWords', function () {
    return JSON.parse(open("../data/searchWords.json"));
});

As that will significantly cut on the number of full copies in memory