Hi,
I'm struggling with the proper use of JSON.stringify and JSON.parse, and hope the Node-RED community can help.
Suppose I have a nicely formatted JSON string, such as:
var JSONString = '{ "Button1" : "ON", "Button2" : "OFF", "Joystick" : {"direction" : 0.45, "force" : 0.81}}';
Using JSON.parse and pushing the resulting object into a msg.payload, I see a nicely formed object with properties Button1, Button2 and Joystick (the latter being expandable to direction and force).
Now I'm in a situation that I have objects Button1, Button2 (those being string objects) and Joystick (an object with properties direction and force).
I'd like to generate what's the equivalent to the above JSONString, however, all my solutions using JSON.stringify end up with nested arrays, which isn't as pretty.
Here's my Node-RED flow to try out and bring my point across. As I said, the question is not specific to Node-RED, but rather reflects on my superficial knowledge of JavaScript...
Any help much appreciated!
Cheers,
Boris
[{"id":"e98a9ba7.801518","type":"inject","z":"da3ad0ce.ec1858","name":"","topic":"","payload":"trigger","payloadType":"str","repeat":"","crontab":"","once":false,"x":90,"y":40,"wires":[["9ca5023a.a77ab8","33055975.a43e8e"]]},{"id":"9ca5023a.a77ab8","type":"function","z":"da3ad0ce.ec1858","name":"fromString","func":"var JSONString = '{ \"Button1\" : \"ON\", \"Button2\" : \"OFF\", \"Joystick\" : {\"direction\" : 0.45, \"force\" : 0.81}}';\n\nmsg.topic = \"from JSON string\"\nmsg.payload = JSON.parse(JSONString);\nreturn msg;","outputs":1,"noerr":0,"x":250,"y":20,"wires":[["6d5c9aae.dd28a4"]]},{"id":"6d5c9aae.dd28a4","type":"debug","z":"da3ad0ce.ec1858","name":"","active":true,"console":"false","complete":"payload","x":430,"y":40,"wires":[]},{"id":"33055975.a43e8e","type":"function","z":"da3ad0ce.ec1858","name":"dynamically","func":"var Button1 = \"ON\";\nvar Button2 = \"OFF\"\nvar Joystick = new Object();\nJoystick.direction = 0.45;\nJoystick.force = 0.81;\n\nvar ListOfObjects = [{\"Button1\" : Button1}, {\"Button2\" : Button2},\n {\"Joystick\" : Joystick} ];\nvar newJSONString = JSON.stringify(ListOfObjects);\n\nmsg.topic = \"dynamically from objects\";\nmsg.payload = JSON.parse(newJSONString);\nreturn msg;","outputs":1,"noerr":0,"x":250,"y":60,"wires":[["6d5c9aae.dd28a4"]]}]