0

I want to return a string in a HTTP response as JSON using express JS. I am trying this but I am getting error. What am I doing wrong?

msg = '{"foo": "bar"}';
msgJSON = JSON.parse(msg);
res.status(200).send(msgJSON);

I need to be a string because it is generated concatenating key-value pairs

4
  • What error are you getting? Commented May 9, 2018 at 21:23
  • Unexpected token ' in JSON at position 1 Commented May 9, 2018 at 21:28
  • do you get that error with the example code you posted, or just with the programmatically built string? I see nothing wrong with what you've posted aside from some extra steps you don't need. Commented May 9, 2018 at 21:30
  • @DanCrews Indeed I was getting the error with the programatically built string. I was doing it wrong but thanks to your answer I managed to solve the issue. Commented May 9, 2018 at 21:51

1 Answer 1

1

Based off your edit, you don't need to parse the object. You can just send the data:

res.set('content-type', 'application/json');
res.status(200).send(msg);
Sign up to request clarification or add additional context in comments.

2 Comments

I forgot to add ' ' in order to be a string, sorry. I updated the question
Thanks, it works. Just by the way, why if I use res.status(200).json(msg) instead of res.status(200).send(msg) the response is between " ": "response"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.