I would like to note that the method name for DOMRect.toJSON (actually the toJSON method of DOMRectReadOnly) is misleading.
It does not return the DOMRect instance as Javascript String Object Notation (so a string), but a plain Object.
So, trying to use the DOMRect.toJSON return value as actual JSON will throw a SyntaxError.
const elementDimensions = JSON.parse(
[someElement].getBoundingClientRect().toJSON()
);
// => Uncaught SyntaxError: "[object Object]" is not valid JSON
// One can of course use ...
const elementDimensions = JSON.parse(
JSON.stringify([someElement].getBoundingClientRect().toJSON())
);
// But that would be, well ... refute the meaning of toJSON
Thanks a ton for sharing this. I would love to take it to the team of technical writers, can you please open an issue here so we can discuss on this topic if there are any more comments.
One small clarification that might be useful for the documentation: toJSON() is expected to return a JavaScript value that can be serialized to JSON, rather than a JSON string directly.
Passing the result of toJSON() directly to JSON.parse() fails because JSON.parse() expects a string containing JSON, not an object.
That said, I agree that a brief note on the MDN page explaining this distinction could help prevent confusion, especially for developers encountering toJSON() for the first time.
Thanks for raising it!
Regards, AC1DST4R Self Employed Developer / Unofficial MDN Support