Type-safe JMESPath implementation for parsing and extracting data from JSON documents in AWS Lambda serverless applications
npx @tessl/cli install tessl/npm-aws-lambda-powertools--jmespath@2.29.0Type-safe JMESPath for AWS Lambda to parse and extract data from JSON documents. Supports AWS event envelopes (SQS, SNS, S3, etc.) and custom functions for JSON parsing, base64 decoding, and decompression.
npm install @aws-lambda-powertools/jmespath// Core search
import { search } from '@aws-lambda-powertools/jmespath';
// Envelopes
import { extractDataFromEnvelope, SQS, SNS, API_GATEWAY_REST } from '@aws-lambda-powertools/jmespath/envelopes';
// Custom functions
import { PowertoolsFunctions } from '@aws-lambda-powertools/jmespath/functions';
// Errors
import { JMESPathError, ParseError, JMESPathTypeError } from '@aws-lambda-powertools/jmespath';import { search } from '@aws-lambda-powertools/jmespath';
const data = { foo: { bar: { baz: 1 } } };
const result = search('foo.bar.baz', data); // 1function search(
expression: string,
data: JSONObject,
options?: { customFunctions?: Functions }
): unknown;Evaluates JMESPath expression against JSON data. Supports all standard JMESPath syntax (projections, filters, multi-select, expressions).
search('foo.bar.baz', { foo: { bar: { baz: 1 } } }); // 1
search('items[?price > `100`]', data); // filtered array
search('[foo, bar]', data); // multi-selectfunction extractDataFromEnvelope<T>(
data: JSONObject,
envelope: string,
options?: { customFunctions?: Functions }
): T;Extracts data from AWS event envelopes. Automatically enables PowertoolsFunctions for JSON parsing, base64, and decompression.
import { extractDataFromEnvelope, SQS } from '@aws-lambda-powertools/jmespath/envelopes';
import type { SQSEvent } from 'aws-lambda';
type Body = { customerId: string };
export const handler = async (event: SQSEvent) => {
const records = extractDataFromEnvelope<Array<Body>>(event, SQS);
for (const { customerId } of records) {
console.log(customerId);
}
};Quick reference for AWS service event patterns:
// API Gateway
API_GATEWAY_REST: 'powertools_json(body)'
API_GATEWAY_HTTP: 'powertools_json(body)'
// Messaging
SQS: 'Records[*].powertools_json(body)'
SNS: 'Records[0].Sns.Message | powertools_json(@)'
// EventBridge
EVENTBRIDGE: 'detail'
CLOUDWATCH_EVENTS_SCHEDULED: 'detail'
// Kinesis
KINESIS_DATA_STREAM: 'Records[*].kinesis.powertools_json(powertools_base64(data))'
// CloudWatch Logs
CLOUDWATCH_LOGS: 'awslogs.powertools_base64_gzip(data) | powertools_json(@).logEvents[*]'
// S3 combinations
S3_SQS: 'Records[*].powertools_json(body).Records[0]'
S3_SNS_SQS: 'Records[*].powertools_json(body).powertools_json(Message).Records[0]'
S3_KINESIS_FIREHOSE: 'records[*].powertools_json(powertools_base64(data)).Records[0]'
S3_SNS_KINESIS_FIREHOSE: 'records[*].powertools_json(powertools_base64(data)).powertools_json(Message).Records[0]'
S3_EVENTBRIDGE_SQS: 'Records[*].powertools_json(body).detail'Three AWS-specific functions for common Lambda data transformations:
import { PowertoolsFunctions } from '@aws-lambda-powertools/jmespath/functions';
// Usage
search('powertools_json(body)', { body: '{"foo":"bar"}' }, {
customFunctions: new PowertoolsFunctions()
}); // { foo: 'bar' }
// Chaining
extractDataFromEnvelope(
{ payload: 'eyJmb28iOiJiYXIifQ==' },
'powertools_json(powertools_base64(payload))'
); // { foo: 'bar' }class PowertoolsFunctions extends Functions {
funcPowertoolsBase64(value: string): string; // Decode base64
funcPowertoolsBase64Gzip(value: string): string; // Decode + decompress gzip
funcPowertoolsJson(value: string): JSONValue; // Parse JSON string
}All standard functions are available. Common ones:
// Numeric: abs, avg, ceil, floor, max, min, sum
search('sum([`1`, `2`, `3`])', {}); // 6
// String: contains, starts_with, ends_with, join
search('join(`, `, [`a`, `b`])', {}); // "a, b"
// Array: length, reverse, sort, to_array
search('sort([`3`, `1`, `2`])', {}); // [1, 2, 3]
// Object: keys, values, merge
search('keys({a: `1`, b: `2`})', {}); // ["a", "b"]
// Type: type, to_number, to_string, not_null
// Advanced with expressions: map, max_by, min_by, sort_by
const data = [{ name: 'Alice', age: 30 }, { name: 'Bob', age: 25 }];
search('max_by(@, &age)', data); // {name: "Alice", age: 30}Full function signatures in Custom Functions.
All errors extend JMESPathError:
import {
JMESPathError, // Base error
LexerError, // Invalid character at lexerPosition
ParseError, // Invalid syntax at lexPosition
ArityError, // Wrong argument count (actualArity vs expectedArity)
JMESPathTypeError, // Wrong type (actualType vs expectedTypes[])
UnknownFunctionError // Function not found
} from '@aws-lambda-powertools/jmespath';
try {
search('invalid..expression', data);
} catch (error) {
if (error instanceof ParseError) {
console.error(`Syntax error at position ${error.lexPosition}`);
}
}type JMESPathParsingOptions = {
customFunctions?: Functions;
};
type JSONObject = JSONArray | JSONValue | object;
type JSONArray = Array<JSONValue>;
// For custom functions
type FunctionSignatureOptions = {
argumentsSpecs: Array<Array<string>>; // [['string'], ['number']]
variadic?: boolean;
};import { extractDataFromEnvelope, API_GATEWAY_REST } from '@aws-lambda-powertools/jmespath/envelopes';
const body = extractDataFromEnvelope<RequestBody>(event, API_GATEWAY_REST);import { extractDataFromEnvelope, SQS } from '@aws-lambda-powertools/jmespath/envelopes';
const messages = extractDataFromEnvelope<Array<MessageBody>>(event, SQS);extractDataFromEnvelope(event, 'powertools_json(powertools_base64(data.payload))');import { PowertoolsFunctions } from '@aws-lambda-powertools/jmespath/functions';
class CustomFunctions extends PowertoolsFunctions {
@PowertoolsFunctions.signature({
argumentsSpecs: [['string']],
variadic: false,
})
public funcCustomDecode(value: string): string {
// custom logic
}
}
search('custom_decode(field)', data, { customFunctions: new CustomFunctions() });