Return JSON

Python example

def handleRequest(request):
    # defines a dictionary object for the JSON content
    json_str = {
        "message": "Python Worker hello world!"
    }

    # a new Response
    return __new__(Response(json_str, {
        'headers' : { 'content-type' : 'application/json;charset=UTF-8' }
    }))

# call the Worker runtime
addEventListener('fetch', (lambda event: event.respondWith(handleRequest(event.request))))

 Note

When running this Worker I ran into the following error: SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

This was fixed by updating the index.py file.

I added a JSON.stringify(json_str) when returning the Response object, this converts a JavaScript value to a JSON string.

def handleRequest(request):
    # defines a dictionary object for the JSON content
    json_str = {
        "message": "Python Worker hello world!"
    }

    # a new Response
    return __new__(Response(JSON.stringify(json_str), {
        'headers' : { 'content-type' : 'application/json;charset=UTF-8' }
    }))

# call the Worker runtime
addEventListener('fetch', (lambda event: event.respondWith(handleRequest(event.request))))

This returns.

{
    "message":"Python Worker hello world!"
}
Last updated on 8 Oct 2020
Published on 8 Oct 2020