Can JSON.stringify convert ANY javascript variable into text? Or are there limitations (functions, prototypes, etc.)?
4 Answers
JSON.stringify(JSON.stringify)
This returns undefined; JSON does not support functions.
JSON.stringify(/JSON.stringify/)
This returns "{}"; JSON.stringify skips non-enumerable properties.
JSON.stringify(JSON)
This returns "{}"; JSON.stringify skips properties that return unsupported values.
JSON.stringify(JSON.JSON = JSON)
This throws an exception; JSON does not support circular references.
Comments
There are two answers to your question:
- Simple answer: No, see various counterexamples (like DOM objects, functions, just try it yourself in a prompt).
- Complicated answer: Yes, JSON.stringify CAN convert ANY javascript expression into any JSON sub-expression. There are no major limitations.
The caveat is it cannot do this by default, and it cannot do so in any standardized way. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify - specifically the replacer argument here https://developer.mozilla.org/en-US/docs/Using_native_JSON#The_replacer_parameter, which is a function that is like:
function(key,value) {
if (SPECIALLOGIC) {
// ... return some special value
// like {__SPECIAL__:'datetime', value:'some_custom_encoding'}
} else
return value;
}
2 Comments
var x = {}; var y = { link: x }; x.link = y; will not get stringified.https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
If undefined, a function, or an XML value is encountered during conversion it is either omitted (when it is found in an object) or censored to null (when it is found in an array).