JSON merging

I have now made a greatly improved version of jsonMerge. It is now aware of cyclic structures, and hence no longer requires infinite CPU cyles to complete (I thought that was a reasonable demand on system ressources, given the task at hand).

Download this example: jsonMerge.zip

Variable json1 initially contains:


Variable json2 initially contains:


Adding cyclic references to json1 and json2:


Test of cyclic references before calling jsonDataHandler.merge(json1, json2):


Test of cyclic references after calling jsonDataHandler.merge(json1, json2):


Result of calling jsonDataHandler.merge(json1, json2) where cyclic references has been removed to allow non-infinite output:


The class LGPL license:
// Author: Michael Schøler, 2008
// LGPL license, use as you like, don't hold me responsible for success or failure though
var jsonDataHandler = {
  merge: function(j1, j2) {
    if (typeof this.merging === "undefined" || this.merging === 0) {
      this.mergeCyclicCheck = [];
      this.merging = 0;
    }
    this.merging += 1;
    if (typeof j1 === "undefined") {
      j1 = {};
    }
    if (typeof j2 === "undefined") {
      j2 = {};
    }
    if (typeof this.mergeCyclicCheck === "undefined") {
      this.mergeCyclicCheck = [];
    }
    var key;
    for (key in j2) if (j2.hasOwnProperty(key)) {
      if (typeof j1[key] === "undefined") {
        j1[key] = j2[key];
      }
      else {
        if (typeof j2[key] === "object") {
          if (this.mergeCyclicCheck.indexOf(j1[key]) >= 0) {
            break;
          }
          this.merge(j1[key], j2[key]);
          this.mergeCyclicCheck.push(j1[key]);
        } 
        else {
          j1[key] = j2[key]; 
        }
      }
    }
    this.merging -= 1;
  }
};