DOMRect.toJSON is misleading

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

I would suggest a line to mention this in the MDN DOMRectReadOnly page

Regards / Kooiinc

[edit] rerouted to MDN topic.

Hello @KooiInc :waving_hand:

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.

Thank you! :folded_hands:

Hi pransh, glad to contribute. Issue submitted.

1 Like

Perfect. Thanks a ton!

Hi @KooiInc !

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.

For example:

const rect = element.getBoundingClientRect();

const dimensions = rect.toJSON(); // Plain object
const json = JSON.stringify(rect); // JSON string

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