为什么在对URL进行编码时JSON编码器会添加转义字符? [英] Why does JSON encoder adds escaping character when encoding URLs?
问题描述
我在PHP中使用json_encode
对URL进行编码
I am using json_encode
in PHP to encode an URL
$json_string = array ('myUrl'=> 'http://example.com');
echo json_encode ($json_string);
上面的代码生成以下JSON字符串:
The above code generates the following JSON string:
{"myUrl":"http:\/\/example.com"}
而不是
{"myUrl":"http://example.com"}
我只是新手,哪个输出正确? JSON解析器能够正确评估第二个输出吗?
I am just newbie, which output is correct? Is JSON parser able to evaluate the second output correctly?
推荐答案
根据 http://www.json.org /,尽管JavaScript并非严格要求,但应该转义该字符:
According to http://www.json.org/, one should escape that character, although it is not strictly necessary in JavaScript:
也请阅读php.net上的此相关的错误报告,以进行简要讨论
Also read this related bug report on php.net for a brief discussion.
请参见 RFC 中的2.5:
所有Unicode字符都可以放置 在引号内,但 必须转义的字符: 引号,反固相线和 控制字符(U + 0000至 U + 001F).
All Unicode characters may be placed within the quotation marks except for the characters that must be escaped: quotation mark, reverse solidus, and the control characters (U+0000 through U+001F).
任何字符都可以转义.
所以听起来好像不需要被转义,但可以这样,并且网站(以及RFC中的文本图)说明它已被转义.
So it doesn't sound like it needs to be escaped, but it can be, and the website (and a text diagram in the RFC) illustrates it as being escaped.
这篇关于为什么在对URL进行编码时JSON编码器会添加转义字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!