-1

For testing purposes I decided to test a function I have written which returns a DOMRect object.

In the console I can see that the DOMRect is intact and has all of its properties. However, when I have JSON.stringify(rect) (where rect is the variable with the return result), I get the empty object {}.

I don’t know whether that means that there’s something special about a DOMRect, or whether JSON.stringify doesn’t do what I thought it would do, which is to serialize the properties of an object.

The question is: why won’t JSON.stringify work on a DOMRect (and will it also fail on some other obects?

FWIW, I am testing on a current Mac, and have tried both Firefox and Webkit.

Manngo
  • 14,066
  • 10
  • 88
  • 110

3 Answers3

2

JSON.stringify() cannot be used on any DOM element - you will need to pull out the data you want and place into an Object. Previously JSON.stringify() on DOM nodes used to result in this error:

TypeError: Converting circular structure to JSON

Now Chrome, Firefox, etc. all output "{}"

hackerrdave
  • 6,486
  • 1
  • 25
  • 29
  • Could you clarify that point? `JSON.stringify` doesn’t work on _any_ dom object? Fair enough, I suppose, but it seems odd — it’s not as if the values are dynamic. The circular structure message seems stranger. – Manngo Feb 06 '17 at 04:28
  • correct - `JSON.stringify()` will not work on any DOM node. see also: http://stackoverflow.com/questions/2303713/how-to-serialize-dom-node-to-json-even-if-there-are-circular-references – hackerrdave Feb 06 '17 at 04:35
  • 1
    Thanks for your help. All I really needed was the content, so I have found it convenient copy the `DOMRect` content into a new object. It also gives me the chance to customise it a bit and polyfill for Certain Browsers. – Manngo Feb 06 '17 at 04:38
-1

JSON.stringify only works on structured data. It does not allow the stringification of functions.

Darkrum
  • 1,325
  • 1
  • 10
  • 27
-1

DOMRect is a function so, JSON.stringify() will not allowed because DOMRect contains 'Virtual' properties. JSON.stringify() depends on Object.key(attr).