Conditional json extraction is throwing error

Hi,
Conditional json extraction is NOT working for below scenario/json:

[
   {
      "companyId":"123",
      "parentCompanyId":"101013",
      "key":12501697,
      "companyName":"abc",
      "statusCode":"AC"
   },
   {
      "companyId":"124",
      "parentCompanyId":"101021",
      "key":12501698,
      "companyName":"def",
      "statusCode":"AC"
   },
   {
      "companyId":"125",
      "parentCompanyId":"102003",
      "key":12501699,
      "companyName":"ghi",
      "statusCode":"AC"
   }
]

In script variable to extract using json as below:

vars["pCompanyId"] = jsonpath.query(
      response.json(),
      "$.[?(@.parentCompanyId=='134070')].companyId"
    )[0];
ERRO[0019] Error: Parse error on line 1:
$.[?(@.rfgCompanyId=='U
--^a
Expecting 'STAR', 'IDENTIFIER', 'SCRIPT_EXPRESSION', 'INTEGER', 'END', got '['
        at parseError (https://jslib.k6.io/jsonpath/1.0.2/index.js:3929:15(16))
        at https://jslib.k6.io/jsonpath/1.0.2/index.js:5129:31(19)
        at parse (https://jslib.k6.io/jsonpath/1.0.2/index.js:3987:32(365))
        at https://jslib.k6.io/jsonpath/1.0.2/index.js:4983:31(35)
        at https://jslib.k6.io/jsonpath/1.0.2/index.js:4959:27(26)
        at file:///<<script_path>>.js:297:49(75)
        at github.com/loadimpact/k6/js/common.Bind.func1 (native)
        at main (file:///<<script_path>>.js:273:17(47))  executor=constant-vus scenario=default source=stacktrace.

Any help would be helpful.

Hi @huligesh.hanumanthap , sorry for the slow response.

I guess you are using https://jslib.k6.io/jsonpath/1.0.2/index.js and it seems like it doesn’t support “$.[” but works perfectly with “$[”:

import jsonpath from "https://jslib.k6.io/jsonpath/1.0.2/index.js";

var a = [
       {
                 "companyId":"123",
                 "parentCompanyId":"101013",
                 "key":12501697,
                 "companyName":"abc",
                 "statusCode":"AC"
              },
       {
                 "companyId":"124",
                 "parentCompanyId":"101021",
                 "key":12501698,
                 "companyName":"def",
                 "statusCode":"AC"
              },
       {
                 "companyId":"125",
                 "parentCompanyId":"102003",
                 "key":12501699,
                 "companyName":"ghi",
                 "statusCode":"AC"
              }
]


var vars = {};
vars["pCompanyId"] = jsonpath.query(
          a,
          "$[?(@.parentCompanyId=='101013')].companyId"
        )[0];
console.log(JSON.stringify(vars));

produces

INFO[0000] {"pCompanyId":"123"}                          source=console
ERRO[0000] no exported functions in script
3 Likes

thanks @mstoykov. Now it is working