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 50length
is 1But 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).
Note that === never causes type coercion, but checks for correct types first and yields false if they are not equal!
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With