2018-03-06 05:26:37 +00:00
|
|
|
const jq = require('jsonpath');
|
|
|
|
|
2018-06-25 17:42:50 +00:00
|
|
|
module.exports.templateTags = [
|
|
|
|
{
|
|
|
|
displayName: 'JSONPath',
|
|
|
|
name: 'jsonpath',
|
|
|
|
description: 'Pull data from JSON strings with JSONPath',
|
|
|
|
args: [
|
|
|
|
{
|
|
|
|
displayName: 'JSON string',
|
|
|
|
type: 'string'
|
|
|
|
},
|
|
|
|
{
|
|
|
|
displayName: 'JSONPath Filter',
|
|
|
|
type: 'string'
|
|
|
|
}
|
|
|
|
],
|
|
|
|
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 {
|
|
|
|
results = jq.query(body, filter);
|
|
|
|
} 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-03-06 05:26:37 +00:00
|
|
|
}
|
2018-06-25 17:42:50 +00:00
|
|
|
];
|