0

I have some json that looks like this:

const json = {
   "name": "Peter",
   "age": 21
}

Then I call JSON.stringify(json) which gives me the following:

'{"name":"Peter","age":21}'

I want to send data from the UI to my server. Currently I am using POSTMAN for this.

POST
http:localhost:8888/user
Body -> JSON

{
  "user": { 
     "details": '{"name":"Peter","age":21}',
     "foo": "bar"
   }
}

details here needs to be a string but when I send over the data I get the following error on the server

SyntaxError: Unexpected token } in JSON at position 114

Does anyone have any ideas here?

1 Answer 1

1

JSON does not allow for single quotes, what you are trying to send is invalid. What you need to do is use double quotes and escape the internal quotes for the JSON key/values:

{
  "user": { 
     "details": "{\"name\":\"Peter\",\"age\":21}",
     "foo": "bar"
   }
}
Sign up to request clarification or add additional context in comments.

5 Comments

thanks Jacob. In reality the details is far bigger. is there any regex trick to do this for me?
if I use the following s.replace(/\"/g, '\\"') I get two escapes and it still doesn't work
I fear you are misunderstanding how escaped characters work, can you please show your full relevant code? Telling me you do a stringify in the original post and then a regex replace in a comment is a bit disorganized and confusing
well the relevant code is the same thing but instead of name and age there are 100s of key/values so i can't really go and manually add the ``. Make sense? I found this tool which helps, but would rather handle this in my own code
I can almost assure you the problem isnt the code, if you sent the object from the frontend directly to the backend, it would likely work fine. The problem is it sounds like you are building an object in the frontend, logging it out (hence losing the escapes) and then copying that string into Postman. Thats why I said I don't think you are understanding escaped characters. Is there a reason you are using Postman and not having the frontend directly call your backend?

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.