Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it correct that JSON.stringify(2) == "2" may return false?

I've found that on Opera 11.50 the expression

 JSON.stringify(2) 

returns an object for which

  • typeof returns "string"
  • constructor.name is String
  • charCodeAt(0) is 50
  • length is 1

But still

alert(JSON.stringify(2) == "2") 

shows "false" in Opera (and the same happens using ===).

Is this a bug or what?

The only way I found to make it compare equal to "2" is calling .substr(0) (for example even adding an empty string still compares different).

like image 402
6502 Avatar asked Aug 14 '11 16:08

6502


People also ask

Does === return false?

Note that === never causes type coercion, but checks for correct types first and yields false if they are not equal!

What is JSON Stringify return?

It should return the value that should be added to the JSON string, as follows: If you return a Number , String , Boolean , or null , the stringified version of that value is used as the property's value. If you return a Function , Symbol , or undefined , the property is not included in the output.

Can JSON Stringify throw an error?

Errors and Edge CasesJSON. stringify() throws an error when it detects a cyclical object. In other words, if an object obj has a property whose value is obj , JSON. stringify() will throw an error.

When should I use JSON Stringify?

The JSON. stringify() method in Javascript is used to create a JSON string out of it. While developing an application using JavaScript, many times it is needed to serialize the data to strings for storing the data into a database or for sending the data to an API or web server.


1 Answers

That definitely looks like a bug.

From the ECMAScript 5.1 specification:

Conforming implementations of JSON.parse and JSON.stringify must support the exact interchange format described in this specification without any deletions or extensions to the format. This differs from RFC 4627 which permits a JSON parser to accept non-JSON forms and extensions.

And:

JSON.stringify produces a String that conforms to the following JSON grammar. JSON.parse accepts a String that conforms to the JSON grammar

It may be that it somehow wraps the string in a "JSONText" type object which still has a typeof of string but that seems very odd.

I would definitely think that the following implementation in this case is the correct one:

JSON.stringify(2) == "2" && JSON.stringify(2) === "2" && JSON.stringify(2) == 2 && JSON.stringify(2) !== 2; true 

According to @6502 (see comment) this is true in:
Chrome; Firefox; IE9; iPad Safari; OsX Safari; the N1 Android browser

The ECMAScript 5.1 specification document: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf

like image 68
Robin Winslow Avatar answered Oct 06 '22 09:10

Robin Winslow