Search code examples
javascriptjqueryjsond3.jsstringify

How to stringify circular JSON object and save it to file?


I'm working on a radial tree diagram in javascript using d3.js and jquery. I use json files to load data into a javascript var. After working on a diagram and making some changes, e.g. changing parent of some nodes, I want to stringify data and save as a json file. When I stringify treeData variable, which includes all json data, and wanted to display it, I receive only the root node stringified. This is my code:

var json = JSON.stringify(treeData.children, function(key,value){
    if(key == "children"){
        return undefined;
    }
    return value;
});
alert("Json: " + json);

Also I don't know why the key is set to "children". My JSON file structure:

{
 "name": "root",
 "children": [
  {
   "name": "child1",
   "children": [ ... ]
  }
 ]
}

Solution

  • The problem is that using tree data will return with a loop and circular data error. Switching key from "children" to "parent" give a json without references to the parents and work properly.