Differences in JSON.stringify result between browsers

不羁岁月 提交于 2020-01-01 08:20:48

问题


When I JSON.stringify() the following code:

var exampleObject = { "name" : "Žiga Kovač", "kraj" : "Žužemberk"};

I get different results between browsers.

IE8 and Google Chrome return:

{"name":"\u017diga Kova\u010d","kraj":"\u017du\u017eemberk"}

While Firefox and Opera return:

{"name":"Žiga Kovač","kraj":"Žužemberk"}

I am using the browser's native JSON implementation in all 4 browsers. If I undefine the native JSON implementation and replace it with the one from json.org, then all browsers return:

{"name":"Žiga Kovač","kraj":"Žužemberk"}

Why is this happening, which result is correct and is it possible to make that all browsers return:

{"name":"\u017diga Kova\u010d","kraj":"\u017du\u017eemberk"}

?


回答1:


These two representations are absolutely equivalent.

The one uses Unicode escape sequences (\uxxxx) to represent a Unicode character, the other uses an actual Unicode character. json.org defines a string as:

string
    - ""
    - "chars"
chars
    - char
    - char chars
char
    - any Unicode character except " or \ or control characters
    - one of: \" \\ \/ \b \f \n \r \t
    - \u four-hex-digits

There is no difference in the strings themselves, only in their representation. This is the same thing HTML does when you use ©, © or © to represent the copyright sign.




回答2:


The 'correct' (visibly) version is a UTF8 string, and the escaped string is an ASCII string with UTF8 escape codes. While the first one can be used in an HTTP body (as long as content-encoding is set to UTF8), the second one can also be used in an HTTP GET request header.

If you want to use the UTF8 version in a GET request, you need to escape it first, using encodeURIComponent.

When the content is received on the server side, the native string implementation will make sure that it contains exactly the same data (from all clients), provided that the HTTP transmission is correct.

Your browser will generally handle the encoding of it, if you send it as an HTTP POST body.




回答3:


Both result's are correct, as long as your first example is encoded in UTF-8.

e.g. \u017d ist just another notation of Ž (017d is the position in UTF8-charset)




回答4:


They are all correct. Some are returning it encoded in UTF-8, and some in ASCII.



来源:https://stackoverflow.com/questions/3862430/differences-in-json-stringify-result-between-browsers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!