3

How can i JSON.stringify the following data-structure?

var Records = {
    1357775376232: {
        pageX: 0,
        pageY: 0,
        scrollLeft: 0,
        scrollTop: 0,
        target: #document,
        type: null,
        value: undefined
    },
    1357775376243: {
        pageX: 69,
        pageY: 10,
        scrollLeft: 0,
        scrollTop: 0,
        target: <a>,
        type: "click",
        value: ""
    }
    // ...etc...
};
yckart
  • 32,460
  • 9
  • 122
  • 129

2 Answers2

4

It looks like this object contains references to document and to an a tag. You won't be able to serialize it until you remove such references.

A simple solution is:

var arrayWithRefs = [...];
var arrayWithout = [];

for (var i = 0; i < arrayWithRefs.length; i++) {
  arrayWithout[i] = {
    safeProperty: arrayWithRefs[i].safeProperty;
    // copy whatever you want, omitting document references
  };
}

var serialized = JSON.stringify(arrayWithout);

And of course there are libraries that can help you to pluck out just the properties you want. I would recommend underscore (general purpose) or cryo (exactly what you're attempting):

hunterloftis
  • 13,386
  • 5
  • 48
  • 50
  • Full-disclosure, I'm the author of this library: https://github.com/hunterloftis/cryo - 'JSON on steroids' - it lets you do things like stringify around DOM elements without problems. Drop-in replacement for JSON.stringify/JSON.parse with lots of unit tests. – hunterloftis Jan 10 '13 at 01:10
0

Instead of using a plain object, use the XPath for the elements.

yckart
  • 32,460
  • 9
  • 122
  • 129