2018-05-27 23:07:09 +02:00
|
|
|
/**
|
|
|
|
* @author Matt C (matt@artemisbot.uk)
|
|
|
|
* @copyright Crown Copyright 2016
|
|
|
|
* @license Apache-2.0
|
|
|
|
*/
|
|
|
|
|
2022-09-09 21:39:28 +02:00
|
|
|
import {JSONPath} from "jsonpath-plus";
|
2019-07-09 13:23:59 +02:00
|
|
|
import Operation from "../Operation.mjs";
|
|
|
|
import OperationError from "../errors/OperationError.mjs";
|
2018-05-27 23:07:09 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* JPath expression operation
|
|
|
|
*/
|
|
|
|
class JPathExpression extends Operation {
|
|
|
|
|
|
|
|
/**
|
|
|
|
* JPathExpression constructor
|
|
|
|
*/
|
|
|
|
constructor() {
|
|
|
|
super();
|
|
|
|
|
|
|
|
this.name = "JPath expression";
|
|
|
|
this.module = "Code";
|
|
|
|
this.description = "Extract information from a JSON object with a JPath query.";
|
2018-08-21 20:07:13 +02:00
|
|
|
this.infoURL = "http://goessner.net/articles/JsonPath/";
|
2018-05-27 23:07:09 +02:00
|
|
|
this.inputType = "string";
|
|
|
|
this.outputType = "string";
|
|
|
|
this.args = [
|
|
|
|
{
|
2022-09-09 21:39:28 +02:00
|
|
|
name: "Query",
|
|
|
|
type: "string",
|
|
|
|
value: ""
|
2018-05-27 23:07:09 +02:00
|
|
|
},
|
|
|
|
{
|
2022-09-09 21:39:28 +02:00
|
|
|
name: "Result delimiter",
|
|
|
|
type: "binaryShortString",
|
|
|
|
value: "\\n"
|
|
|
|
},
|
|
|
|
{
|
|
|
|
name: "Prevent eval",
|
|
|
|
type: "boolean",
|
|
|
|
value: true,
|
|
|
|
description: "Evaluated expressions are disabled by default for security reasons"
|
2018-05-27 23:07:09 +02:00
|
|
|
}
|
|
|
|
];
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param {string} input
|
|
|
|
* @param {Object[]} args
|
|
|
|
* @returns {string}
|
|
|
|
*/
|
|
|
|
run(input, args) {
|
2022-09-09 21:39:28 +02:00
|
|
|
const [query, delimiter, preventEval] = args;
|
|
|
|
let results, jsonObj;
|
2018-05-27 23:07:09 +02:00
|
|
|
|
|
|
|
try {
|
2022-09-09 21:39:28 +02:00
|
|
|
jsonObj = JSON.parse(input);
|
2018-05-27 23:07:09 +02:00
|
|
|
} catch (err) {
|
|
|
|
throw new OperationError(`Invalid input JSON: ${err.message}`);
|
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
2022-09-09 21:39:28 +02:00
|
|
|
results = JSONPath({
|
|
|
|
path: query,
|
|
|
|
json: jsonObj,
|
|
|
|
preventEval: preventEval
|
|
|
|
});
|
2018-05-27 23:07:09 +02:00
|
|
|
} catch (err) {
|
|
|
|
throw new OperationError(`Invalid JPath expression: ${err.message}`);
|
|
|
|
}
|
|
|
|
|
|
|
|
return results.map(result => JSON.stringify(result)).join(delimiter);
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
export default JPathExpression;
|