Programming

Lambda Function To Calc The Fields In A JSON Document

Below is a Lambda function to return the number of fields in a JSON document. This Lambda function expects the JSON document in a body field of the event. It loads the JSON document using the standard json.loads() and counts the number of fields by retrieving the keys of the loaded JSON object and calculating the length. The expected response would be a 200 status code if successful, with the number of fields as a string in the response body (which can easily be changed to an int, but made sense to leave as str so if it got some wacky data I’d see that). If the JSON document is invalid and cannot be loaded, a 400 status code is returned with an error message in the response body. In that case, consider linting it with something like the https://github.com/krypted/tinyconverters/blob/main/LintJSON.py script I posted. The script lives at or see below:

import json

def count_json_fields(event, context):
    # Retrieve the JSON document from the Lambda event
    json_document = event['body']

    # Load the JSON document
    try:
        data = json.loads(json_document)
    except json.JSONDecodeError:
        return {
            'statusCode': 400,
            'body': 'Invalid JSON document'
        }

    # Count the number of fields in the JSON document
    num_fields = len(data.keys())

    return {
        'statusCode': 200,
        'body': str(num_fields)
    }