0

I just simply to use JSON.stringify({"a": "123"}) to stringify a json

In chrome, the " semicolon will not be escaped, it will echo

JSON.stringify({"a": "123"})
"{"a":"123"}"

But if I use the same code in safari, the " semicolon will be escaped, like this

JSON.stringify({"a": "123"})
"{\"a\":\"123\"}"

I want to know the reason about why the chrome and safari have the different result

qiuyuntao
  • 2,314
  • 4
  • 19
  • 24
  • 2
    That's just different representations in different consoles, they are the same string. Try `.length` – Bergi Feb 26 '19 at 15:20
  • 1
    Possible duplicate of [Why does javascript object show different values in console in Chrome, Firefox, Safari?](https://stackoverflow.com/questions/8249136/why-does-javascript-object-show-different-values-in-console-in-chrome-firefox) – Anis D Feb 26 '19 at 15:20

1 Answers1

5

It's not about JSON.stringify, it's about how the console displays value literals.

Safari chooses to make the entire line a valid literal. I.e. you could copy-paste the entire line into Javascript source code, and it'd be valid.

Safari displays "foo\"bar"

Chrome opts to just add decorative "" marks around the line to signify that it's a string value, but displays only the string contents as-is, without making it into a valid literal.

Chrome displays "foo"bar"

The advantage of Safari's method is that you can copy-paste values as code, while Chrome's advantage is that you can read a string's contents without needing to mentally parse it according to string escaping rules.

deceze
  • 510,633
  • 85
  • 743
  • 889