Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are all javascript variable JSON-serializable?

Can JSON.stringify convert ANY javascript variable into text? Or are there limitations (functions, prototypes, etc.)?

like image 582
edeboursetty Avatar asked Dec 10 '25 00:12

edeboursetty


2 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.

like image 166
SLaks Avatar answered Dec 11 '25 13:12

SLaks


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;
}
like image 39
ninjagecko Avatar answered Dec 11 '25 12:12

ninjagecko