[英]JSON.parse fails to create an object from a string
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. 我正在使用ruby on rails创建cookie,该cookie将包含请求的参数的数组作为字符串返回给视图。 However, I get the following error when I JSON.parse that string:
但是,当我使用JSON.parse该字符串时,出现以下错误:
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? 我该如何解决?
The string is not valid json. 该字符串是无效的json。
It is uri encoded so decode it using decodeURIComponent()
它是uri编码的,因此请使用
decodeURIComponent()
对其进行解码
JSON.parse(decodeURIComponent('%7B%22specialty%22%3A%5B%22Anesthesiology%22%5D%7D'))
You need to use decodeURIComponent
to first decode the string. 您需要使用
decodeURIComponent
首先对字符串进行解码。
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, ie the object in the form of a string.
解码后,您将获得键值对,即字符串形式的对象。 Now you can use
JSON.parse
to form the Javascript object. 现在,您可以使用
JSON.parse
形成Javascript对象。
Other answers are correct in saying that the payload is URI encoded, but decodeURIComponent
is only a javascript method. 其他答案是正确的,说有效负载是URI编码的,但是
decodeURIComponent
只是一个javascript方法。 To decode it ruby-side, use URI.unescape
. 要对其进行解码,请使用
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. 您说您正在使用rails,因此URI对象应该已经可用,但是如果您不使用rails,则需要先
require 'uri'
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.