我知道非标准的%uxxxx方案,但这似乎不是明智的选择,因为该方案已被W3C拒绝.
一些有趣的例子:
心中的人物.如果我在浏览器中输入:
http://www.google.com/search?q=?
Run Code Online (Sandbox Code Playgroud)
然后复制并粘贴它,我看到这个URL
http://www.google.com/search?q=%E2%99%A5
Run Code Online (Sandbox Code Playgroud)
这使得它看起来像Firefox(或Safari)正在这样做.
urllib.quote_plus(x.encode("latin-1"))
'%E2%99%A5'
Run Code Online (Sandbox Code Playgroud)
这是有道理的,除了不能用Latin-1编码的东西,比如三点字符.
…
Run Code Online (Sandbox Code Playgroud)
如果我输入URL
http://www.google.com/search?q=…
Run Code Online (Sandbox Code Playgroud)
进入我的浏览器然后复制粘贴,我明白了
http://www.google.com/search?q=%E2%80%A6
Run Code Online (Sandbox Code Playgroud)
背部.这似乎是做的结果
urllib.quote_plus(x.encode("utf-8"))
Run Code Online (Sandbox Code Playgroud)
这是有道理的,因为...不能用Latin-1编码.
但后来我不清楚浏览器是如何用UTF-8或Latin-1解码的.
因为这似乎含糊不清:
In [67]: u"…".encode('utf-8').decode('latin-1')
Out[67]: u'\xc3\xa2\xc2\x80\xc2\xa6'
Run Code Online (Sandbox Code Playgroud)
有效,所以我不知道浏览器是如何用UTF-8或Latin-1解码的.
使用我需要处理的特殊字符做什么是正确的?
以下是Embarcadero帮助的示例代码(http://docwiki.embarcadero.com/RADStudio/XE5/en/JSON):
您可以使用以下代码片段之一将JSON字符串表示形式转换为JSON.
使用ParseJSONValue:
procedure ConsumeJsonString;
var
LJSONObject: TJSONObject;
begin
LJSONObject := nil;
try
{ convert String to JSON }
LJSONObject := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(GJSONString), 0) as TJSONObject;
{ output the JSON to console as String }
Writeln(LJSONObject.ToString);
finally
LJSONObject.Free;
end;
Run Code Online (Sandbox Code Playgroud)
该方法失败,并在as行上抛出类无效类型!
使用Parse:
procedure ConsumeJsonBytes;
var
LJSONObject: TJSONObject;
begin
LJSONObject := nil;
try
LJSONObject := TJsonObject.Create;
{ convert String to JSON }
LJSONObject.Parse(BytesOf(GJSONString), 0);
{ output the JSON to console as String }
Writeln(LJSONObject.ToString);
finally
LJSONObject.Free;
end; …Run Code Online (Sandbox Code Playgroud)