0

I am using ruby on rails to create a cookie that returns an array containing the params of the request back to the view as a string. However, I get the following error when I JSON.parse that string:

JSON.parse('%7B%22specialty%22%3A%5B%22Anesthesiology%22%5D%7D')

Uncaught SyntaxError: Unexpected token % in JSON at position 0

how do I fix this?

3 Answers 3

3

The string is not valid json.

It is uri encoded so decode it using decodeURIComponent()

JSON.parse(decodeURIComponent('%7B%22specialty%22%3A%5B%22Anesthesiology%22%5D%7D'))
Sign up to request clarification or add additional context in comments.

Comments

1

Other answers are correct in saying that the payload is URI encoded, but decodeURIComponent is only a javascript method. To decode it ruby-side, use URI.unescape.

JSON.parse(URI.unescape('%7B%22specialty%22%3A%5B%22Anesthesiology%22%5D%7D'))

You say you're using rails, so the URI object should already be available, but if you weren't using rails you would need to require 'uri' first.

1 Comment

Uncaught SyntaxError: is likely a javascript error.
1

You need to use decodeURIComponent to first decode the string.

JSON.parse(decodeURIComponent(
  '%7B%22specialty%22%3A%5B%22Anesthesiology%22%5D%7D'
));

As the string is encoded. Once you decode it, you get the key value pair, i.e. the object in the form of a string. Now you can use JSON.parse to form the Javascript object.

Comments

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.