Problem parsing JSON Data

This may be more a JSON parsing question than a Particle question, but I’ve got a problem. I am sending data using this:

Particle.publish("hello-app-engine", "{\"num1\": 5, \"num2\": 8}");

It shows up in the event as {"num1" : 5, "num2" : 8}

When I send it to a Node.js App Engine project on Google Cloud Platform, and print out

  app.post('/sum', (req, res) => {
    let num1 = req.body.data.num1;
    let num2 = req.body.data.num2;
    let sum = num1 + num2;
    res.write(`You sent ${JSON.stringify(req.body.data)}\n`); 
    res.write(`and ${req.body.data.num1}\n`)
    res.write(`=======>{"num1":${num1}, "num2":${num2}, "sum":${sum}}`);
    res.end();
  });

I am getting something very weird:

"You sent \"{\\\"num1\\\": 5, \\\"num2\\\": 8}\"\nand undefined\n=======>{\"num1\":undefined, \"num2\":undefined, \"sum\":NaN}"

So, what’s with the extra backslashes?? I am at a loss, any help would be hugely appreciated.

Not sure what you are trying to achieve as is not really clear
your request is still a string, not an object. so you don’t have an access to req.members yet, and you shouldn’t use JSON.stringify() as req. is an string already. You have to use JSON.parse() instead to make an JS Object to be able to work with it.
Try this:

app.post('/sum', (req, res) => {
    let obj = JSON.parse(req.body.data);
    let sum = obj.num1 + obj.num2;
    res.write(`You sent ${req.body.data)}`); 
    res.write(`and ${obj.num1}`)
    res.write(`=======>JSON.stringify({num1:${obj.num1}, num2:${obj.num2}, sum:${sum}}));
    res.end();
  });

Best,
Arek

3 Likes

Oh, thank you so much, Arek - I just assumed that req was a JS object - I owe you one!

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.