Stdout to http response as JSON

Hi all,

Right now, I'm creating a REST API with node-red which took an HTTP in as the input, process the HTTP get parameters with python using exec, and try to send the response with JSON format.

In exec node, the output is sending out as stdout with Python print function, but I'm stuck in how to format the stdout as JSON string. Link print("{'error': 123}") with template of {{ payload}} then Set Headers and http response does not work in my case.

Any suggestions would be appreciated. I've the freedom to either format the print function from my python code or directly modifly the node-red template.

Edited: I figured out. The template of {{ payload}} is not necessary and it would try to escape the quotation marks. Simply print('{"error": 123, "dfsfsfs": 456}') and link exec to http response is good enough.

1 Like

I expect there is a Python library somewhere that will do that for you.

However, this seems a bit sideways. Why not just do it in Node-RED which can handle JSON natively?

For your python code,

import json

# rest of your code

return_obj = {"error": 123, "other_value": 456}
print(json.dumps(return_obj))

Should handle all your cases and handle nested objects and lists too without you needing to worry about using the correct quotes in all the places.

As for the rest, sounds like this is something that can either be done fully in NR, or fully in Python depending on your approach.

Though you might want to replace the smart quotes with standard ones :slight_smile:

“
"
1 Like

Oops, I missed those while typing too quickly, will edit. Thanks :stuck_out_tongue:

Thank you. I used exactly the same approach and solved this problem.

1 Like

My python code needs to process data from database and machine learning models, I'm not very familiar with using node-red/JS to achieve the same objectives, that's why I'm only using node-red to do a simple parse HTTP query task.