2021-10-06 22:01:43 +00:00
|
|
|
const { JSONPath } = require('jsonpath-plus');
|
2018-03-06 05:26:37 +00:00
|
|
|
|
2018-06-25 17:42:50 +00:00
|
|
|
module.exports.templateTags = [
|
|
|
|
{
|
|
|
|
displayName: 'JSONPath',
|
|
|
|
name: 'jsonpath',
|
2018-07-23 17:24:41 +00:00
|
|
|
description: 'pull data from JSON strings with JSONPath',
|
2018-06-25 17:42:50 +00:00
|
|
|
args: [
|
|
|
|
{
|
|
|
|
displayName: 'JSON string',
|
2018-12-12 17:36:11 +00:00
|
|
|
type: 'string',
|
2018-06-25 17:42:50 +00:00
|
|
|
},
|
|
|
|
{
|
|
|
|
displayName: 'JSONPath Filter',
|
2019-08-21 00:24:18 +00:00
|
|
|
encoding: 'base64', // So it doesn't cause syntax errors
|
2018-12-12 17:36:11 +00:00
|
|
|
type: 'string',
|
|
|
|
},
|
2018-06-25 17:42:50 +00:00
|
|
|
],
|
|
|
|
run(context, jsonString, filter) {
|
|
|
|
let body;
|
|
|
|
try {
|
|
|
|
body = JSON.parse(jsonString);
|
|
|
|
} catch (err) {
|
|
|
|
throw new Error(`Invalid JSON: ${err.message}`);
|
|
|
|
}
|
2018-03-06 05:26:37 +00:00
|
|
|
|
2018-06-25 17:42:50 +00:00
|
|
|
let results;
|
|
|
|
try {
|
2021-10-06 22:01:43 +00:00
|
|
|
results = JSONPath({ json: body, path: filter });
|
2018-06-25 17:42:50 +00:00
|
|
|
} catch (err) {
|
|
|
|
throw new Error(`Invalid JSONPath query: ${filter}`);
|
|
|
|
}
|
2018-03-06 05:26:37 +00:00
|
|
|
|
2018-06-25 17:42:50 +00:00
|
|
|
if (results.length === 0) {
|
|
|
|
throw new Error(`JSONPath query returned no results: ${filter}`);
|
|
|
|
}
|
2018-03-06 05:26:37 +00:00
|
|
|
|
2018-06-25 17:42:50 +00:00
|
|
|
return results[0];
|
2018-12-12 17:36:11 +00:00
|
|
|
},
|
|
|
|
},
|
2018-06-25 17:42:50 +00:00
|
|
|
];
|