2

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

0

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

Not entirely true (regarding complicated answer) - JSON.stringify will not convert circular data structures. On example: var x = {}; var y = { link: x }; x.link = y; will not get stringified.
kamituel: Thank you; was aware, probably should have put a sidenote about that. Technically (with effort) I think one can reify the circular references into special records (by traversing the tree, putting everything into a hashmap), then rebuild the references when unserializing.
2

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

Comments

1

The limitations include stringifying objects that contain circular references which trigger exceptions.

JSON.stringify(document);
// TypeError: Converting circular structure to JSON

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.