Webdev return csv

Simple question,

I'm already using the webdev module to return a json file.

In PowerBI, often it would be much easier to parse a csv. So the question is: is it possible to return a csv instead of a json in a doGet?

Thanks.

Sure, set the response key to the CSV text and the contentType key to text/csv.

https://docs.inductiveautomation.com/display/DOC81/Web+Dev

If it's a really big CSV, you may want to get to the servlet object directly and stream the results; e.x (this is obviously JSON, but encoding CSV manually is easy enough)

    rows = 20
    columns = xrange(1, 9)
    request["servletResponse"].setContentType("application/json")
    writer = request["servletResponse"].writer

    writer.write("[")
    for i in xrange(rows):
        writer.write(system.util.jsonEncode({'value%d' % j: j for j in columns}))
        if (i < rows - 1):
            writer.write(",")

    writer.write("]")

I don't think this example is streaming anything because you don't call flush at any point.

1 Like

Ah, good point. You'd probably want to flush every X thousand rows or something. :man_shrugging:

Thanks to both!

Webdev is really awsome.