1
votes

I am trying to convert click information to a JSON for storage using

$(document).click(function(e){
  url = '/recordclick';
  $.post(url, {'clickData':JSON.stringify(e)});
});

but it seems that the click event has one or more circular references in it because I get the error

Uncaught TypeError: Converting circular structure to JSON

Is there a way to easily convert the click event into something without circular references, that is, without manually removing each of the circular referencing properties?

2
Don't do that. What part of the event do you actually need? - SLaks
why you need to stringify such big event object into json? - MarkoCen
why not just create an object with only the stuff you need and then do the JSON.stringify - Khaled Garbaya
@SLaks Not sure what information will be most useful to our machine learning algorithm, so I'm trying to save as much as possible. Storage space is not an issue. - wogsland
@KhaledGarbaya That is what I want to do, but without knowing what I need a priori. - wogsland

2 Answers

2
votes

You may use Douglas Crockford's JSON.decycle function to make a deep copy of the event object before encoding it to JSON.

Souce code here: https://github.com/douglascrockford/JSON-js/blob/master/cycle.js

Here is a quote from the source code of the function's description

Make a deep copy of an object or array, assuring that there is at most one instance of each object or array in the resulting structure. The duplicate references (which might be forming cycles) are replaced with an object of the form {"$ref": PATH} where the PATH is a JSONPath string that locates the first occurance. [...]

As you've included JSON.decycle your code can be adjusted like this:

$(document).click(function(e) {
    var url = '/recordclick', // let's declare variables as local!
        dec = JSON.decycle(e);
    $.post(url, { 'clickData': JSON.stringify(dec) });
});
1
votes

the stringify function accepts a filter function as a second param, so I think you can do this.

JSON.stringify( event, function( key, value) {
  if( key == 'circularReference1' || key == 'circularReference2') { return value.id;}
  else {return value;}
}