How to I return JSON from a Google Cloud Function

Cloud Functions has Flask available under the hood, so you can use it's jsonify function to return a JSON response.

In your function:

from flask import jsonify

def my_function(request):
    data = ...
    return jsonify(data)

This will return a flask.Response object with the application/json Content-Type and your data serialized to JSON.

You can also do this manually if you prefer to avoid using Flask:

import json

def my_function(request):
    data = ...
    return json.dumps(data), 200, {'Content-Type': 'application/json'}

You don't need Flask per se

import json

def my_function(request):
    data = ...
    return json.dumps(data), 200, {'ContentType': 'application/json'}

Make 200 whatever response code is suitable, eg. 404, 500, 301, etc.

If you're replying from a HTML AJAX request

return json.dumps({'success': True, 'data': data}), 200, {'ContentType': 'application/json'}

to return an error instead for the AJAX request

return json.dumps({'error': True}), 404, {'ContentType': 'application/json'}