You might have events that contains encoded JSON payloads as string, base64, or even in compressed format. It is a common use case to decode and extract them partially or fully as part of your Lambda function invocation.
Lambda Powertools also have utilities like validation, idempotency, or feature flags where you might need to extract a portion of your data before using them.
Info
Envelope is the terminology we use for the JMESPath expression to extract your JSON object from your data input.
You can use the extract_data_from_envelope function along with any JMESPath expression.
123456789
fromaws_lambda_powertools.utilities.jmespath_utilsimportextract_data_from_envelopefromaws_lambda_powertools.utilities.typingimportLambdaContextdefhandler(event:dict,context:LambdaContext):payload=extract_data_from_envelope(data=event,envelope="powertools_json(body)")customer=payload.get("customerId")# now deserialized...
We provide built-in envelopes for popular JMESPath expressions used when looking to decode/deserialize JSON objects within AWS Lambda Event Sources.
123456789
fromaws_lambda_powertools.utilities.jmespath_utilsimportextract_data_from_envelope,envelopesfromaws_lambda_powertools.utilities.typingimportLambdaContextdefhandler(event:dict,context:LambdaContext):payload=extract_data_from_envelope(data=event,envelope=envelopes.SNS)customer=payload.get("customerId")# now deserialized...
This sample will decode the value within the body key of an API Gateway event into a valid JSON object to ensure the Idempotency utility processes a JSON object instead of a string.
Deserializing JSON before using as idempotency key
This should only be used for advanced use cases where you have special formats not covered by the built-in functions.
For special binary formats that you want to decode before applying JSON Schema validation, you can bring your own JMESPath function and any additional option via jmespath_options param.
In order to keep the built-in functions from Powertools, you can subclass from PowertoolsFunctions:
1 2 3 4 5 6 7 8 9101112131415161718
fromaws_lambda_powertools.utilities.jmespath_utilsimport(PowertoolsFunctions,extract_data_from_envelope)fromjmespath.functionsimportsignatureclassCustomFunctions(PowertoolsFunctions):@signature({'types':['string']})# Only decode if value is a stringdef_func_special_decoder(self,s):returnmy_custom_decoder_logic(s)custom_jmespath_options={"custom_functions":CustomFunctions()}defhandler(event,context):# use the custom name after `_func_`extract_data_from_envelope(data=event,envelope="special_decoder(body)",jmespath_options=**custom_jmespath_options)...