def get_record_as_json(cur, tablename, row_id):
    """
    Get a single record from the database, by id, as json.
    """

    # IMPORTANT NOTE: Only use this function in trusted input.  Never on data
    # being created by users.  The table name is not escaped.
    q = """
    SELECT row_to_json(new_with_table)
    FROM (SELECT {t}.*, '{t}' AS tablename FROM {t}) new_with_table
    WHERE id=%s;""".format(
        t=tablename,
    )
    cur.execute(q, (row_id,))
    return cur.fetchone()[0]