-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
Copy pathJPathExpression.mjs
71 lines (61 loc) · 1.69 KB
/
JPathExpression.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
* @author Matt C (matt@artemisbot.uk)
* @copyright Crown Copyright 2016
* @license Apache-2.0
*/
import {JSONPath} from "jsonpath-plus";
import Operation from "../Operation.mjs";
import OperationError from "../errors/OperationError.mjs";
/**
* 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.";
this.infoURL = "http://goessner.net/articles/JsonPath/";
this.inputType = "string";
this.outputType = "string";
this.args = [
{
name: "Query",
type: "string",
value: ""
},
{
name: "Result delimiter",
type: "binaryShortString",
value: "\\n"
}
];
}
/**
* @param {string} input
* @param {Object[]} args
* @returns {string}
*/
run(input, args) {
const [query, delimiter] = args;
let results, jsonObj;
try {
jsonObj = JSON.parse(input);
} catch (err) {
throw new OperationError(`Invalid input JSON: ${err.message}`);
}
try {
results = JSONPath({
path: query,
json: jsonObj
});
} catch (err) {
throw new OperationError(`Invalid JPath expression: ${err.message}`);
}
return results.map(result => JSON.stringify(result)).join(delimiter);
}
}
export default JPathExpression;